gpt4 book ai didi

python - Matplotlib - 显示 .plot 和 .bar 的图例

转载 作者:行者123 更新时间:2023-12-04 07:16:00 24 4
gpt4 key购买 nike

下面的代码

import numpy as np
import matplotlib.pyplot as plt

x = [1,2,3,4,5]
y = np.array([0.1,0.5,0.4,0.3,0.4])
p = [0.6,0.3,0.15,0.1,0.5]

f, axes = plt.subplots(1,2,figsize=(20,4))

axes[0].plot(x,y)
axes[0].plot(x,y+0.05)
axes[0].bar(x,p,color="r",alpha=0.2)
axes[1].plot(x,y)
axes[1].plot(x,y+0.05)
axes[1].bar(x,p,color="r",alpha=0.2)

aliases = ["data1","data2","probabiity"]

handles = axes[1].get_lines()
f.legend(handles, aliases, loc='upper center', ncol=len(aliases), fontsize=10, bbox_to_anchor=(0.5, 1))
plt.savefig("temp.pdf")
产生下图。它只显示图例 data1data2对于折线图,但条形图的图例为空。如何让 matplotlib 在同一个图例中包含条形图?
enter image description here

最佳答案

问题是

handles = axes[1].get_lines()
显然 bar 的结果不是一条线。您还需要包含补丁集合对象:
handles = axes[1].get_lines() + axes[1].containers
请参阅此处以供引用:
  • How do I get all bars in a matplotlib bar chart?
  • How to get a BarContainer Object from an AxesSubplot object in matplotllib?
  • 关于python - Matplotlib - 显示 .plot 和 .bar 的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68756451/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com