Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.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
matplotlib图例显示“0”;“10位艺术家的容器对象”;代替标签_Matplotlib_Legend - Fatal编程技术网

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})
    
    您可以添加数据(包含代码之前的行),因为这样可以更容易地复制您的问题。谢谢