首页 > 解决方案 > Matplotlib 条形图图例仅显示一项

问题描述

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

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

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()

标签: pythonmatplotlib

解决方案


显示来自 pd.DataFrame 的数据:

  • 图例 = 列名
  • x_tics = 索引

您可以将countsSeries 转换为 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()

这里这里


推荐阅读