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

2024-04-19 09:47:01 发布

您现在位置:Python中文网/ 问答频道 /正文

这似乎是重复的,但我发誓我试图找到一个兼容的答案。在

我有一组相同3个样品的不同性质的柱状图。所以我想要一个有这些树样本名字的图例。在

像“h1”和“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')

然后我用了:

^{pr2}$

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


Tags: stepplth1histlabelh3yes图例
1条回答
网友
1楼 · 发布于 2024-04-19 09:47:01

你有两个问题。首先,你误解了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

相关问题 更多 >