How to add custom annotations, from the dataframe, to a stacked bar chart?

后端 未结 2 632
無奈伤痛
無奈伤痛 2020-12-10 08:18

I\'m plotting a cross-tabulation of various offices within certain categories. I\'d like to put together a horizontal stacked bar chart where each office and its value is la

2条回答
  •  难免孤独
    2020-12-10 08:48

    Figured it out. If I iterate through the columns of each row of the dataframe I can build up a list of the labels I need that matches the progression of the rectangles in ax.patches. Solution below:

    labels = []
    for j in df.columns:
        for i in df.index:
            label = str(j)+": " + str(df.loc[i][j])
            labels.append(label)
    
    patches = ax.patches
    
    for label, rect in zip(labels, patches):
        width = rect.get_width()
        if width > 0:
            x = rect.get_x()
            y = rect.get_y()
            height = rect.get_height()
            ax.text(x + width/2., y + height/2., label, ha='center', va='center')
    

    Which, when added to the code above, yields:

    Now to just deal with re-arranging labels for bars that are too small.

提交回复
热议问题