2014-02-13 48 views
1

這可能看起來像重複,但我發誓我試圖找到一個兼容的答案。如何在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') 

圖例出現,但是是空的。有任何想法嗎?

回答

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

+0

+1不知道代理的藝術家。 – zhangxaochen

+0

@ zhangxaochen傳說中的代碼令人難以置信的強大和酷,但令人難以置信的不透明。看看它如何做處理程序調度,你可以做驚人的事情。 – tacaswell

相關問題