Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Python图例属性错误_Python 3.x_Matplotlib - Fatal编程技术网

Python 3.x Python图例属性错误

Python 3.x Python图例属性错误,python-3.x,matplotlib,Python 3.x,Matplotlib,为什么这里会出现与plt.plot标签相关的错误 fig = plt.figure() ax = plt.gca() barplt = plt.bar(bins,frq,align='center',label='Dgr') normplt = plt.plot(bins_n,frq_n,'--r', label='Norm'); ax.set_xlim([min(bins)-1, max(bins)+1]) ax.set_ylim([0, max(frq)]) plt.xlabel('Dgr'

为什么这里会出现与plt.plot标签相关的错误

fig = plt.figure()
ax = plt.gca()
barplt = plt.bar(bins,frq,align='center',label='Dgr')
normplt = plt.plot(bins_n,frq_n,'--r', label='Norm');
ax.set_xlim([min(bins)-1, max(bins)+1])
ax.set_ylim([0, max(frq)])
plt.xlabel('Dgr')
plt.ylabel('Frequency')
plt.show()
plt.legend(handles=[barplt,normplt])
这是我得到的错误:
“list”对象没有属性“get_label”

,因为
plt.plot
可以一次打印多行,所以它返回
line2D
对象的列表,即使您只打印一行(即在您的情况下,长度为1的列表)。抓取图例的句柄时,只需使用此列表的第一项(实际的
line2D
对象)

有(至少)两种方法可以解决此问题:

1) 调用
plt.plot
时,在
normplt
后添加逗号,以便仅将列表中的第一项存储在
normplt

barplt = plt.bar(bins,frq,width,align='center',label='Dgr')
normplt, = plt.plot(bins_n,frq_n,'--r', label='Norm')   # note the comma after normplt

print normplt
# Line2D(Norm)    <-- This is the line2D object, not a list, so we can use it in legend
...
plt.legend(handles=[barplt,normplt])

在新的matplotlib版本中添加了(3.1.0) 用于创建散点图的图例

现在,PathCollection提供了一个方法legend_elements(),用于自动获取散点图的句柄和标签。这使得为散点图创建图例变得非常简单

因此,您还可以使用:

N=45
x、 y=np.random.rand(2,N)
c=np.random.randint(1,5,size=N)
s=np.random.randint(10220,size=N)
图,ax=plt.子批次()
散射=最大散射(x,y,c=c,s=s)
#使用散点中的独特颜色生成图例
legend1=ax.legend(*scatter.legend_elements(),loc=“左下”,title=“Classes”)
ax.添加艺术家(legend1)
#生成一个图例,其横截面为散点的大小
手柄、标签=分散。图例元素(prop=“size”,alpha=0.6)
legend2=ax.图例(手柄、标签、loc=“右上角”、title=“尺寸”)
plt.show()

如果发布完整的回溯,您的问题会得到改进。这将明确导致问题的原因,并帮助人们回答这个问题。它也会帮助你解决你自己的问题。如果你的问题写得更仔细一些,它可能已经收到了一张赞成票。感谢你让我们知道它是刚刚添加的——我来这里想知道为什么我在旧版本中得到的“PathCollection”对象没有属性“legend_elements”。
barplt = plt.bar(bins,frq,width,align='center',label='Dgr')
normplt = plt.plot(bins_n,frq_n,'--r', label='Norm')

print normplt
# [<matplotlib.lines.Line2D object at 0x112076710>]  
# Note, this is a list containing the Line2D object. We just want the object, 
# so we can use normplt[0] in legend
...
plt.legend(handles=[barplt,normplt[0]])