Pandas、条形图注释

标签 pandas matplotlib plot charts

如何正确给 Pandas 条形图添加注释?

我正在关注Bar Chart Annotations with Pandas and MPL ,但不知何故我无法将其放入我自己的代码中 - this is as far as I can go 。怎么了?

我还发现了以下代码from here :

def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                '%d' % int(height),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)

但我也不知道如何将其应用到我的代码中。请帮忙。

更新:

谢谢@CT Zhu的回答。但是,在您的水平条中,您仍然将文本放置在条的顶部,但我需要文本显示在它们内部或沿着它们,就像我引用的文章中的那样,

enter image description here

他/她说的地方,

"I am very parital to horizontal bar charts, as I really think they are easier to read, however, I understand that a lot of people would rather see this chart implemented in a regular bar chart. So, here is the code to do that; you will notice that a few things have changed in order to create the annotation"*

最佳答案

看来您的autolabel函数需要一个补丁列表,假设您的绘图仅将这些条形作为其补丁,我们可以这样做:

df = pd.DataFrame({'score':np.random.randn(6),
                   'person':[x*3 for x in list('ABCDEF')]})

def autolabel(rects):
    x_pos = [rect.get_x() + rect.get_width()/2. for rect in rects]
    y_pos = [rect.get_y() + 1.05*rect.get_height() for rect in rects]
    #if height constant: hbars, vbars otherwise
    if (np.diff([plt.getp(item, 'width') for item in rects])==0).all():
        scores = [plt.getp(item, 'height') for item in rects]
    else:
        scores = [plt.getp(item, 'width') for item in rects]
    # attach some text labels
    for rect, x, y, s in zip(rects, x_pos, y_pos, scores):
        ax.text(x, 
                y,
                '%s'%s,
                ha='center', va='bottom')

ax = df.set_index(['person']).plot(kind='barh', figsize=(10,7), 
              color=['dodgerblue', 'slategray'], fontsize=13)

ax.set_alpha(0.8)
ax.set_title("BarH")#,fontsize=18)
autolabel(ax.patches)

enter image description here

ax = df.set_index(['person']).plot(kind='bar', figsize=(10,7), 
              color=['dodgerblue', 'slategray'], fontsize=13)

ax.set_alpha(0.8)
ax.set_title("Bar")#,fontsize=18)
autolabel(ax.patches)

enter image description here

关于Pandas、条形图注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34111620/

相关文章:

python - 如何在水平条形图中添加百分比?

python - 从散点图拟合数据

matlab - 如何在 MATLAB 中绘制一维绘图?

R - 绘制六边形镶嵌

python - 将具有分层列索引的宽格式 pandas DataFrame 转换为整齐格式

python - 比较两列值并从第一列获取不同的值

python - 根据last_valid_index值过滤pandas DataFrame

python - 给定指定顺序,获取列中所有重复元素的索引

python - 自动设置 x 轴格式

java - 来自 Java 的 R