2015-09-07 34 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)'中。这有帮助吗? –