Python: Plotting percentage in seaborn bar plot

后端 未结 4 1077
离开以前
离开以前 2021-01-14 20:52

For a dataframe

import pandas as pd
df=pd.DataFrame({\'group\':list(\"AADABCBCCCD\"),\'Values\':[1,0,1,0,1,0,0,1,0,1,0]})

I am trying to pl

4条回答
  •  無奈伤痛
    2021-01-14 21:17

    You can follow these steps so that you can see the count and percentages on top of the bars in your plot. Check the example outputs down below

    with_hue function will plot percentages on the bar graphs if you have the 'hue' parameter in your plots. It takes the actual graph, feature, Number_of_categories in feature, and hue_categories(number of categories in hue feature) as a parameter.

    without_hue function will plot percentages on the bar graphs if you have a normal plot. It takes the actual graph and feature as a parameter.

    def with_hue(plot, feature, Number_of_categories, hue_categories):
        a = [p.get_height() for p in plot.patches]
        patch = [p for p in plot.patches]
        for i in range(Number_of_categories):
            total = feature.value_counts().values[i]
            for j in range(hue_categories):
                percentage = '{:.1f}%'.format(100 * a[(j*Number_of_categories + i)]/total)
                x = patch[(j*Number_of_categories + i)].get_x() + patch[(j*Number_of_categories + i)].get_width() / 2 - 0.15
                y = patch[(j*Number_of_categories + i)].get_y() + patch[(j*Number_of_categories + i)].get_height() 
                ax.annotate(percentage, (x, y), size = 12)
        plt.show()
    
    def without_hue(plot, feature):
        total = len(feature)
        for p in ax.patches:
            percentage = '{:.1f}%'.format(100 * p.get_height()/total)
            x = p.get_x() + p.get_width() / 2 - 0.05
            y = p.get_y() + p.get_height()
            ax.annotate(percentage, (x, y), size = 12)
        plt.show()
    

提交回复
热议问题