【问题标题】:Matplotlib barchart legend only shows one itemMatplotlib 条形图图例仅显示一项
【发布时间】:2020-02-05 13:54:25
【问题描述】:

为条形图创建图例时,仅将列表的第一个元素添加到图例中。

我尝试通过分组数据框打印图例,条形图是出现的直方图

df = pd.DataFrame({'mod': biomarkers})
counts =df.groupby('mod', as_index=False)
counts.size().plot(kind='bar',width=1.0)

names = np.array(counts.describe())[:,2]
counts = np.array(counts.describe())[:,3]
plt.legend(list(names))
plt.show()

【问题讨论】:

  • 确实,一个带有 n 个条形的条形图提供了一个图例条目。如果您想要 n 个图例条目,您需要自己 create them 或绘制 n 个条形图。

标签: python matplotlib


【解决方案1】:

显示来自 pd.DataFrame 的数据:

  • 图例 = 列名
  • x_tics = 索引

您可以将counts Series 转换为 DataFrame 并转置。

fig, ax = plt.subplots()
df = pd.DataFrame({'mod': ['a','b','c','a','a','c']})
counts = df.groupby('mod', as_index=False)

counts_df = counts.size().to_frame().T
counts_df.plot(kind='bar', width=1.0, ax=ax)
# without plt.legend()

请参阅 herehere

【讨论】:

    猜你喜欢
    • 2021-01-19
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2020-01-02
    • 2019-05-12
    • 2015-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多