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

时间:2014-02-13 01:57:25

标签: python matplotlib legend

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

我有一组相同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')

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

1 个答案:

答案 0 :(得分:1)

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