我正在尝试为我的stackplot添加一个图例。我知道您不能以正常方式执行此操作,因此我按照this similar post中的说明操作,但仍然存在错误。
x=data[:,-1]
y1=map(int,data[:,1])
y2=map(int,data[:,2])
y3=map(int,data[:,3])
y4=map(int,data[:,4])
y5=map(int,data[:,5])
y6=map(int,data[:,6])
y7=map(int,data[:,7])
y8=map(int,data[:,8])
y9=map(int,data[:,9])
y10=map(int,data[:,0])
xnew=np.linspace(0,len(x),50)
smooth_y1=spline(np.arange(len(x)),y1,xnew)
smooth_y2=spline(np.arange(len(x)),y2,xnew)
smooth_y3=spline(np.arange(len(x)),y3,xnew)
smooth_y4=spline(np.arange(len(x)),y4,xnew)
smooth_y5=spline(np.arange(len(x)),y5,xnew)
smooth_y6=spline(np.arange(len(x)),y6,xnew)
smooth_y7=spline(np.arange(len(x)),y7,xnew)
smooth_y8=spline(np.arange(len(x)),y8,xnew)
smooth_y9=spline(np.arange(len(x)),y9,xnew)
smooth_y10=spline(np.arange(len(x)),y10,xnew)
plt.stackplot(np.arange(50),smooth_y1,smooth_y2,smooth_y3,smooth_y4,smooth_y5,smooth_y6,smooth_y7,smooth_y8,smooth_y9,smooth_y10)
plt.ylim([0,30])
plt.legend([smooth_y1,smooth_y2,smooth_y3,smooth_y4,smooth_y5,smooth_y6,smooth_y7,smooth_y8,smooth_y9,smooth_y10],['hfsdkjfhs','sldjfhsdkj','sdrtryf','sdfsd','sdkjf','sdfsd','sdrtdf','sfsd','sdaaafs','sdffghs'])
plt.show()
但是图例的行上会出现错误。它说
File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 3381, in legend
ret = gca().legend(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 4778, in legend
self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\legend.py", line 366, in __init__
self._init_legend_box(handles, labels)
File "C:\Python27\lib\site-packages\matplotlib\legend.py", line 606, in _init_legend_box
handler = self.get_legend_handler(legend_handler_map, orig_handle)
File "C:\Python27\lib\site-packages\matplotlib\legend.py", line 546, in get_legend_handler
if orig_handle in legend_handler_keys:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
有谁知道如何解决这个问题?
答案 0 :(得分:6)
from matplotlib.patches import Rectangle
label_list = ['hfsdkjfhs','sldjfhsdkj','sdrtryf','sdfsd','sdkjf','sdfsd','sdrtdf','sfsd','sdaaafs','sdffghs']
x = data[:, -1]
xnew=np.linspace(0,len(x),50)
smoothed_data = [spline(np.arange(len(x)),data[:, j%10],xnew)
for j in range(1, 11)]
# get a figure and axes
fig, ax = plt.subplots()
# make the stack plot
stack_coll = ax.stackplot(xnew, smoothed_data)
# set the ylim
ax.set_ylim([0,30])
# make proxy artists
proxy_rects = [Rectangle((0, 0), 1, 1, fc=pc.get_facecolor()[0]) for pc in stack_coll]
# make the legend
ax.legend(proxy_rects, label_list)
# re-draw the canvas
plt.draw()