Modify a bar plot into a staked plot keeping the original values
13:11 14 Feb 2023

I have a pandas DataFrame containing the percentage of students that have a certain skill in each subject stratified according to their gender

iterables = [['Above basic','Basic','Low'], ['Female','Male']]
index = pd.MultiIndex.from_product(iterables, names=["Skills", "Gender"])
df = pd.DataFrame(data=[[36,36,8,8,6,6],[46,46,2,3,1,2],[24,26,10,11,16,13]], index=["Math", "Literature", "Physics"], columns=index)
print(df)

Output:

       Skill       Above basic    Basic          Low
       Gender    Female Male   Female Male   Female Male
Math                36   36      8    8        6    6
Literature          46   46      2    3        1    2
Physics             24   26     10   11       16   13

Next I want to see how the skills are distributed according to the subjects

# Plot how the skills are distributed according to the subjects
df.sum(axis=1,level=[0]).plot(kind='bar')
df.plot(kind='bar')

Enter image description here

Now I would like to add the percentage of Male and Female to each bar in a stacked manner.. eg. for the fist bar ("Math", "Above basic") it should be 50/50. For the bar ("Literature", "Basic") it should be 40/60, for the bar ("Literature","Low") it should be 33.3/66.7 and so on...

How can I do it?

python pandas matplotlib bar-chart plot-annotations