我有一个 pandas DataFrameGroupBy 对象,我正在像这样绘制...
grouped.sum().plot(kind='bar')
这给出了...
但我想要更多这样的东西......
我只是想知道如何向每列以及可能的表格添加数据标签?
最佳答案
要在条形图顶部添加值标签,您可以循环遍历每个索引中的列,并使用 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/