python - 添加数据标签 - matplotlib 条形图

标签 python matplotlib pandas

我有一个 pandas DataFrameGroupBy 对象,我正在像这样绘制...

grouped.sum().plot(kind='bar')

这给出了...

enter image description here

但我想要更多这样的东西......

enter image description here

我只是想知道如何向每列以及可能的表格添加数据标签?

最佳答案

要在条形图顶部添加值标签,您可以循环遍历每个索引中的列,并使用 text显示值,如下所示:

df = DataFrame(rand(3,2), columns=['A', 'B'])
ax = df.plot(table=True, kind='bar', title='Random')
for i, each in enumerate(df.index):
    for col in df.columns:
        y = df.ix[each][col]
        ax.text(i, y, y)

您可能需要调整文本标签坐标以获得更好的对齐方式等。

<小时/>

为了显示网格表,pandas 从 0.14+ 开始支持表格。

您可以阅读有关 Plotting table HERE 的更多信息

Plotting with matplotlib table is now supported in DataFrame.plot() and Series.plot() with a table keyword. The table keyword can accept bool, DataFrame or Series. The simple way to draw a table is to specify table=True. Data will be transposed to meet matplotlib’s default layout.

fig, ax = plt.subplots(1, 1)
df = DataFrame(rand(5, 3), columns=['a', 'b', 'c'])
ax.get_xaxis().set_visible(False)   # Hide Ticks
df.plot(table=True, ax=ax)

Also, you can pass different DataFrame or Series for table keyword. The data will be drawn as displayed in print method (not transposed automatically). If required, it should be transposed manually as below example.

fig, ax = plt.subplots(1, 1)
ax.get_xaxis().set_visible(False)   # Hide Ticks
df.plot(table=np.round(df.T, 2), ax=ax)

关于python - 添加数据标签 - matplotlib 条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26760636/

相关文章:

python - 为什么我的 RNN 不学习?

python - 解析时无法收到电子邮件

python - matplotlib,savefig : DPI setting is ignored

python - 改变 Pandas 图的颜色条

python - 将数据集划分为训练和测试后将标签转换为指标矩阵

python - 基于内容的过滤推荐系统中连续特征的错误处理

python - 使用 BeautifulSoup 和正则表达式解析时出现意外结果

python - 我可以在 rcParams 中设置 spine 和 ticks 吗?

python - pandas/python 中的 k-means/x-means(或其他?)聚类

python - 如何在 pandas 中跳过两个不同的范围