[英]How to define a single legend for a set of subplots on matplotlib?
这看似重复,但我发誓我试图找到一个兼容的答案。
我有一组相同的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.