matplotlib图例显示“0”;“10位艺术家的容器对象”;代替标签
下面的代码正确地生成了绘图和图例,但是图例不显示指定的matplotlib图例显示“0”;“10位艺术家的容器对象”;代替标签,matplotlib,legend,Matplotlib,Legend,下面的代码正确地生成了绘图和图例,但是图例不显示指定的标签文本,而是显示“10位艺术家的容器对象” ax = plt.subplot(212) plt.tight_layout() l1= plt.bar(X+0.25, Y1, 0.45, align='center', color='r', label='A', edgecolor='black', hatch="/") l2= plt.bar(X, Y2, 0.45, align='center', color='b', la
标签
文本,而是显示“10位艺术家的容器对象”
ax = plt.subplot(212)
plt.tight_layout()
l1= plt.bar(X+0.25, Y1, 0.45, align='center', color='r', label='A', edgecolor='black', hatch="/")
l2= plt.bar(X, Y2, 0.45, align='center', color='b', label='N',hatch='o', fill=False)
ax.autoscale(tight=True)
plt.xticks(X, X_values)
ymax1 = max(Y1) + 1
ymax2 = max(Y2) + 1
ymax = max(ymax1,ymax2)+1
plt.ylim(0, ymax)
plt.grid(True)
plt.legend([l1,l2], loc='upper right', prop={'size':20})
输出如下所示:
如何在图例上正确显示每个条的标签(如
plt.bar()
函数中指定的)?问题源于混合使用plt.legend()
的两种方法。您有两个选择:
ax.get\u legend\u handles\u labels()
将传递给plt.bar()的label
参数填入它们
plt.legend()
,如下所示:
plt.legend([l1,l2], ["A", "N"], loc='upper right', prop={'size':20})
如果要自动填充图例,可以使用以下命令在绘图及其标签中查找可用于图例的对象:
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels, loc='upper right', prop={'size':20})
您可以添加数据(包含代码之前的行),因为这样可以更容易地复制您的问题。谢谢