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

后端 未结 2 629
無奈伤痛
無奈伤痛 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:41

    You could have also just changed the function annotateBars() to:

    def annotateBars(row, ax=ax):
        curr_value = 0 
        for col in row.index:
            value = row[col]
            if (str(value) != 'nan'):
                ax.text(curr_value + (value)/2, labeltonum(row.name), col+","+str(value), ha='center',va='center')
                curr_value += value
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题