0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

percentage should be 0%, 10%, 50%, 100% and x-axis should show the values of columns A,B,C,D,E,F with the relevant values.
@testenthu what you want is unclear, please provide a mockup/schematic of the expected graph as edit to your question
"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." -> this seems to match the above graph. A,B,C,D,E,F as x-axis, stacked counts as Y-axis.
I added a second option, but this doesn't really match the description in the question. Please clarify.
In the above 1st option, I want percentage as y-axis label and add actual counts on the bar's.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.