2015-09-07 28 views
1

我想使用matplotlib自定義傳說。 example in the matplotlib documentation不適用於我的設置。這也不是。自定義傳說matplotlib不工作

from matplotlib import pyplot as plt 
import matplotlib.patches as mpatches 

fig, ax = plt.subplots() 

patch1 = mpatches.Patch(color='#a6cee3', label='Blue') 
patch2 = mpatches.Patch(color='#1f78b4', label='Bluerish') 
patch3 = mpatches.Patch(color='#33a02c', label='Greener') 
patch4 = mpatches.Patch(color='#fdbf6f', label='Kind of orange') 
patch5 = mpatches.Patch(color='#ff7f00', label='Orange') 

all_handles = (patch1, patch2, patch3, patch4, patch5) 

leg = ax.legend(all_handles) 

ax.add_artist(leg) 
plt.show() 

如何讓它產生所需的圖例?

我使用的是Mac OSX 10.10.3,Python 2.7.6,Matplotlib 1.3.1。

回答

2

您應該將handles參數設置爲ax.legend明確:

leg = ax.legend(handles=all_handles) 

我覺得你的代碼的問題是,第一(位置)參數legend否則視爲你希望的對象序列標籤,你沒有任何。

enter image description here

+0

這給了我'AttributeError的: 'NoneType' 對象有沒有屬性「set_axes''。 –

+0

我沒有得到任何錯誤,但這對我來說仍然不起作用,要麼以後不調用'plt.draw'。 @P機器人,其中的功能是那個錯誤? – askewchan

+0

從'ax.legend()',錯誤的調用跟蹤'ax.add_artist(leg)',它給出了add_artist中的/Library/Python/2.7/site-packages/matplotlib-override/matplotlib/axes.pyc錯誤(self,a)'在下面的行(1454)'a.set_axes(self)'中。這有幫助嗎? –