gpt4 book ai didi

python - 如何在 matplotlib 上为一组子图定义单个图例?

转载 作者:太空宇宙 更新时间:2023-11-03 18:34:59 25 4
gpt4 key购买 nike

这可能看起来像重复,但我发誓我试图找到兼容的答案。

我有一组相同 3 个样本的不同属性的直方图。所以我想要一个带有这些树样本名称的图例。

我尝试在所有直方图中定义相同的标签('h1'、'h2' 和 'h3'),如下所示:

plt.subplot(121)
plt.hist(variable1[sample1], histtype = 'step', normed = 'yes', label = 'h1')
plt.hist(variable1[sample2], histtype = 'step', normed = 'yes', label = 'h2')
plt.hist(variable1[sample3], histtype = 'step', normed = 'yes', label = 'h3')

plt.subplot(122)
plt.hist(variable2[sample1], histtype = 'step', normed = 'yes', label = 'h1')
plt.hist(variable2[sample2], histtype = 'step', normed = 'yes', label = 'h2')
plt.hist(variable2[sample3], histtype = 'step', normed = 'yes', label = 'h3')

然后我用了:

plt.legend( ['h1', 'h2', 'h3'], ['Name Of Sample 1', 'Name Of Sample 2', 'Name Of Sample 3'],'upper center')

图例出现,但为空。有什么想法吗?

最佳答案

你有两个问题。首先,您误解了 label 的作用。它不会标记要通过该名称访问的艺术家,但会在您不带任何参数调用 legend 时提供 legend 使用的文本。第二个问题是 bar 没有自动生成的图例处理程序。

fig, (ax1, ax2) = plt.subplots(1, 2)

h1 = ax1.hist(variable1[sample1], histtype='step', normed='yes', label='h1')
h2 = ax1.hist(variable1[sample2], histtype='step', normed='yes', label='h2')
h3 = ax1.hist(variable1[sample3], histtype='step', normed='yes', label='h3')

ha = ax2.hist(variable2[sample1], histtype='step', normed='yes', label='h1')
hb = ax2.hist(variable2[sample2], histtype='step', normed='yes', label='h2')
hc = ax2.hist(variable2[sample3], histtype='step', normed='yes', label='h3')

# this gets the line colors from the first set of histograms and makes proxy artists
proxy_lines = [matplotlib.lines.Line2D([], [], color=p[0].get_edgecolor()) for (_, _, p) in [h1, h2, h3]]

fig.legend(proxy_lines, ['label 1', 'label 2', 'label 3'])

另请参阅http://matplotlib.org/users/legend_guide.html#using-proxy-artist

关于python - 如何在 matplotlib 上为一组子图定义单个图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21743719/

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