Skip to main content
 首页 » 编程设计

python之显示来自数据框不同列的堆积条形图的每种颜色的值

2025年05月04日13JustinYoung

这是我的数据框:

          6month  final-formula     Question Text  numPatients6month 
286231       1       0.031730        CI_FINANCE                977 
286270       1       0.147390            CI_MJO                977 
286276       1       0.106448  CI_CONCENTRATING                977 
286700       2       0.010323            CI_MJO                775 
286323       2       0.018065        CI_FINANCE                775 
286401       2       0.034839  CI_CONCENTRATING                775 
286228       3       0.032020  CI_CONCENTRATING                812 
286238       3       0.061576            CI_MJO                812 
286292       3       0.008621        CI_FINANCE                812 
286690       4       0.008097            CI_MJO                741 
286342       4       0.005398        CI_FINANCE                741 
286430       4       0.060729  CI_CONCENTRATING                741 
286481       5       0.009840        CI_FINANCE                813 
287441       5       0.008610            CI_MJO                813 
286362       5       0.041820  CI_CONCENTRATING                813 
286360       6       0.021622  CI_CONCENTRATING                740 
286492       6       0.017568        CI_FINANCE                740 
286494       6       0.014865            CI_MJO                740 
286482       7       0.015464        CI_FINANCE                776 
286483       7       0.042526            CI_MJO                776 
286599       7       0.011598  CI_CONCENTRATING                776 
286361       8       0.024490  CI_CONCENTRATING                735 
286989       8       0.004082        CI_FINANCE                735 
286402       8       0.021769            CI_MJO                735 
287119       9       0.003916        CI_FINANCE                766 
286408       9       0.011749            CI_MJO                766 
286399       9       0.019582  CI_CONCENTRATING                766 
286267      10       0.019337  CI_CONCENTRATING                724 
286249      10       0.037293            CI_MJO                724 
286810      10       0.008287        CI_FINANCE                724 

我已将此数据框绘制为堆叠条形图。 此堆叠条形图基于 (6month,final-formula)。

如您所见,数据框中有 numPatients6month。 我想在每个类别的堆积条上显示这个数字。 例如:

这是我的条形图:

所以根据上面的堆叠条,我想在第一个条中显示 977 蓝色,CI_Finance 显示 977,橙色.

不同于 this问题,因为它不是堆积条, 也不同于 this ,因为我要显示另一列 (numPatients6month),它位于我的数据框中,而不是 y 轴 中的列。 y 轴是 final-formula,但我想在每个堆叠条的每种颜色上显示 numPatients6month。

作为信息,我用这段代码绘制了上面的图:

df = dffinal.drop('numPatients6month', 1).groupby(['6month','Question Text']).sum().unstack('Question Text') 
 
df.columns = df.columns.droplevel() 
ax=df.plot(kind='bar', stacked=True) 
import matplotlib.pyplot as plt 
 
plt.xticks(range(0,10), ['6month','1 year','1.5 year','2 year','2.5 year','3 year','3.5 year','4 year','4.5 year','5 year'], fontsize=8, rotation=45) 
 
plt.title('Cognitive Impairement-Stack bar') 
plt.show() 

谢谢,:)

请您参考如下方法:

这是一种方法:

ax=df.plot(kind='bar', stacked=True) 
#loop to add the text 
list_values = (dffinal['numPatients6month'].tolist()[::3]  
                + dffinal['numPatients6month'].tolist()[1::3]  
                + dffinal['numPatients6month'].tolist()[2::3]) 
for rect, value in zip(ax.patches, list_values): 
    h = rect.get_height() /2. 
    w = rect.get_width() /2. 
    x, y = rect.get_xy() 
    ax.text(x+w, y+h,value,horizontalalignment='center',verticalalignment='center') 
#same than your code 
plt.xticks(range(0,10), ['6month','1 year','1.5 year','2 year','2.5 year','3 year','3.5 year','4 year','4.5 year','5 year'], fontsize=8, rotation=45) 
plt.title('Cognitive Impairement-Stack bar') 
plt.show() 

list_values 是从列 'numPatients6month' 中获取值的顺序与 ax.patches 中的 rect 和结果是:

但是因为有些条形图很小,结果并不是很容易阅读。

编辑:关于循环,ax.patches 包含有关您绘制的所有条形图的信息,因此对于我命名为 rect 的每个条形图,get_xy 获取栏左下角的位置,使用 get_height (r. get_width) 获取栏的高度 (r.width)。所以 (x+w, y+h) 给出条形中间的坐标,您可以在其中使用函数 添加文本 value(来自 list_values) ax.text(参数horizo​​ntalalignment和verticalalignment是让文字居中)

编辑 2:更通用的方法,感谢@SpghttCd 获取 list_values

list_values = (dffinal.drop('final-formula', 1).groupby(['6month','Question Text']).sum() 
               .unstack('Question Text').fillna(0).astype(int).values.flatten('F')) 
for rect, value in zip(ax.patches, list_values): 
    if value != 0: 
        h = rect.get_height() /2. 
        w = rect.get_width() /2. 
        x, y = rect.get_xy() 
        ax.text(x+w, y+h,value,horizontalalignment='center',verticalalignment='center')