添加数据标签 - matplotlib条形图

时间:2014-11-05 15:17:31

标签: python matplotlib pandas

我有一个像我这样的pandas DataFrameGroupBy对象......

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

给出了......

enter image description here

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

enter image description here

我只是想知道如何为每列添加数据标签,也可能知道表格?

1 个答案:

答案 0 :(得分:3)

要在条形图顶部添加值标签,您可以遍历每个索引中的列,并使用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

的更多信息
  

DataFrame.plot()现在支持使用matplotlib表进行绘图   和带有table关键字的Series.plot()。 table关键字可以接受   bool,DataFrame或Series。绘制表格的简单方法是   指定table = True。数据将被转置以满足matplotlib的要求   默认布局。

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)
  

此外,您可以为表关键字传递不同的DataFrame或Series。   将以打印方法显示的数据绘制数据(未转置   自动)。如果需要,应按如下方式手动转置   示例

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