gpt4 book ai didi

python - Matplotlib Stackplot 图例错误

转载 作者:行者123 更新时间:2023-11-28 21:21:58 24 4
gpt4 key购买 nike

我正在尝试为堆栈图添加图例。我知道您不能以正常方式进行操作,所以我按照 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()

有人知道怎么解决吗?

最佳答案

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()

关于python - Matplotlib Stackplot 图例错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20336881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com