注释pandas中堆叠水平条的值

at1*_*623 4 python matplotlib pandas

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

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)
Run Code Online (Sandbox Code Playgroud)

问题是我使用的注释方法给出了x起点而不是每个段的值.我希望能够为每个条形的每个分段的中心注释每个分段的值.

编辑:为了清楚起见,我希望实现的是这样的,其中值为每个段水平(和垂直)居中:

在此输入图像描述

任何帮助,将不胜感激.

Jam*_*mes 6

您可以使用修补程序bbox获取所需的信息.

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')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述