如何使用Pandas在条形图中的条形图上绘制值?

时间:2014-11-05 09:26:08

标签: python pandas

我正在使用Pandas绘制条形图,但我想在条形图上绘制每个条形图的值。我该怎么办呢?

这是我想要实现的一个例子,但当然我希望数字在条形图上是垂直的而不是像我在这里那样水平。

enter image description here

1 个答案:

答案 0 :(得分:0)

以下是一个例子:

import pandas as pd
import matplotlib.pyplot as plt
ix3 = pd.MultiIndex.from_arrays([['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'], ['foo', 'foo', 'bar', 'bar', 'foo', 'foo', 'bar', 'bar']], names=['letter', 'word'])
df3 = pd.DataFrame({'data1': [3, 2, 4, 3, 2, 4, 3, 2], 'data2': [6, 5, 7, 5, 4, 5, 6, 5]}, index=ix3)
gp3 = df3.groupby(level=('letter', 'word'))
means = gp3.mean()
errors = gp3.std()
fig, ax = plt.subplots()
means.plot(yerr=errors, ax=ax, kind='bar')

for rect in ax.patches:
    bbox = rect.get_bbox()
    x = 0.5 * (bbox.x0 + bbox.x1)
    y = 0.5 * (bbox.y0 + bbox.y1)
    text = "{:g}".format(bbox.y1)
    ax.text(x, y, text,
            va="center", ha="center", 
            rotation=90, fontsize="x-large", color="w")

输出:

enter image description here