【问题标题】:pandas python legend not showing all color categories熊猫python图例未显示所有颜色类别
【发布时间】:2020-07-18 14:51:17
【问题描述】:

我正在尝试使用数据框值绘制图表,我在数据框中有三列,第一列是图表的图例值,第二列是 x 轴,第三列是 y 轴。当我绘制图表时,它只显示图例中的一个类别而不是全部,它只显示一种颜色

这是我的数据框

这是我的代码

ax1 = graphdf.plot(kind='bar', x='Bottles', y='bottle Avg')
figures = graphdf['fig'].tolist()
ax1.legend(labels=figures, fancybox=True, shadow=True)
for p in ax1.patches:
    label1 = "{:.1f}".format(p.get_height())
    ax1.annotate(label1, xy=(p.get_x() * 1.015, p.get_height() * 1.015))

但这只是在标签中显示 1 个类别而不是全部。

这是输出,我想在图例中显示所有类别

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    在这种用法中,pandas.DataFrame.plot.bar 只调用了一次 matplotlib.pyplot.bar,创建了具有单个标签的单个补丁集合。仅指定标签的matplotlib.axes.Axes.legend 签名只是将标签分配给“现有绘图元素”。由于plt.bar 创建了一个“绘图元素”,因此只创建了一个图例条目。您可以通过使用 ax.legend 的第三个调用签名轻松解决此问题,其中 both 指定了标签和句柄,即

    ax = df.plot(kind='bar', x='Bottles', y='bottle Avg')
    ax.legend(labels=df['fig'].tolist(), handles=ax.patches, fancybox=True, shadow=True)
    for p in ax.patches:
        ax.annotate("{:.1f}".format(p.get_height()), xy=(p.get_x() * 1.015, p.get_height() * 1.015))
    

    【讨论】:

      猜你喜欢
      • 2021-05-29
      • 1970-01-01
      • 2014-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多