Search code examples
pythonpandasdataframestacked-chart

Stacked bar plot for a DataFrame


I have a below table in a DataFrame. I want to visualize it in a stacked bar plot.

Percentage A B C D E F
0% 10 20 50 60 100 90
10% 89 87 65 87 89 88
50% 87 876 89 978 6 0
100% 89 78 89 89 54 34

For the above table, I want to get the stacked bar chart with x-axis as columns A,B,C,D,E,F and y-axis as Percentage Counts.

For example, x-axis column A has stacked bar with 10, 89, 87, 89 for the percentages.

I want output to be like enter image description here


Solution

  • Since you want dummy bars, you have to craft a dummy DataFrame:

    tmp = df.set_index('Percentage').T
    X = np.repeat(100/tmp.shape[1], tmp.shape[1])
    
    ax = tmp.notna().mul(X, axis=1).plot.bar(stacked=True)
    ax.legend(bbox_to_anchor=(1.0, 1.0))
    ax.set_yticks(np.cumsum(X)-X[0]/2, tmp.columns)
    
    for k, c in zip(tmp, ax.containers):
        ax.bar_label(c, labels=tmp[k], label_type='center')
    

    Output:

    [pandas dummy stack bars1


    Original answer

    Set percentage as index (set_index), transpose, and plot the stacked bars (plot.bar with stacked=True):

    df.set_index('Percentage').T.plot.bar(stacked=True)
    

    Output:

    pandas stacked bars

    If you want to group by percentage, skip the transpose and use barh:

    df.set_index('Percentage').plot.barh(stacked=True)
    

    Output:

    pandas horizontal stacked bars