注释 pandas 中堆叠水平条的值 [英] Annotate values for stacked horizontal bar in pandas

查看:66
本文介绍了注释 pandas 中堆叠水平条的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试注释使用熊猫创建的堆叠水平条形图的值.当前代码如下

将pandas导入为pd导入matplotlib.pyplot作为plt将numpy导入为npd = {'group 1':[1、2、5、7、4、5、10],'组 2': [5, 6, 1, 8, 2, 6, 2],第3组":[12、2、2、4、4、8、4]}df = pd.DataFrame(d)ax = df.plot.barh(stacked = True,figsize =(10,12))对于ax.patches中的p:ax.annotate(str(p.get_x()),xy =(p.get_x(),p.get_y()+ 0.2))plt.legend(bbox_to_anchor =(0,-0.15),loc = 3,prop = {'size':14},frameon = False)

问题是我使用的注释方法给出了x个起点,而不是每个段的值.我希望能够在每个小节的每个小节的中心注释每个小节的值.

I'm trying to annotate the values for a stacked horizontal bar graph created using pandas. Current code is below

import pandas as pd 
import matplotlib.pyplot as plt
import numpy as np

d = {'group 1': [1, 2, 5, 7, 4, 5, 10],
     'group 2': [5, 6, 1, 8, 2, 6, 2],
     'group 3': [12, 2, 2, 4, 4, 8, 4]}
df = pd.DataFrame(d)

ax = df.plot.barh(stacked=True, figsize=(10,12))

for p in ax.patches:
    ax.annotate(str(p.get_x()), xy=(p.get_x(), p.get_y()+0.2))

plt.legend(bbox_to_anchor=(0, -0.15), loc=3, prop={'size': 14}, frameon=False)

The problem is the annotation method I used gives the x starting points and not the values of each segment. I'd like to be able to annotate values of each segment in the center of each segment for each of the bars.

example

edit: for clarity, what I would like to achieve is something like this where the values are centered horizontally (and vertically) for each segment:

enter image description here

Any help would be appreciated.

解决方案

You can use the patches bbox to get the information you want.

ax = df.plot.barh(stacked=True, figsize=(10, 12))
for p in ax.patches:
    left, bottom, width, height = p.get_bbox().bounds
    ax.annotate(str(width), xy=(left+width/2, bottom+height/2), 
                ha='center', va='center')

这篇关于注释 pandas 中堆叠水平条的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆