I am trying to obtain a stacked and grouped horizontal bar plot in Python:
female_numbers_2015 = [20882, 31322, 52204, 52205, 31322, 20881]
female_numbers_2018 = [20882, 31322, 52204, 52205, 31322, 20881]
male_numbers_2015 = [11352, 17080, 28380, 28380, 17028, 11351]
male_numbers_2018 = [11454, 17181, 28636, 28634, 17181, 11454]
total_numbers_2015 = [306669]
total_numbers_2018 = [323356]
percent_males_2015 = [i /j * 100 for i,j in zip(male_numbers_2015, total_numbers_2015)]
percent_females_2015 = [i /j * 100 for i,j in zip(female_numbers_2015, total_numbers_2015)]
percent_males_2018 = [i /j * 100 for i,j in zip(male_numbers_2018, total_numbers_2018)]
percent_females_2018 = [i /j * 100 for i,j in zip(female_numbers_2018, total_numbers_2018)]
index = ['Poorest 10%', '10-25%', '25-50%', '50-75%', '75-90%', 'Richest 10%']
df = pd.DataFrame({'percent_females_2015': percent_females_2015,'percent_males_2015': percent_males_2015,
'percent_females_2018': percent_females_2018,'percent_males_2018': percent_males_2018}, index=index)
x = np.arange(len(index))
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.barh(x = {male_numbers_2015, female_numbers_2015}, x - width/2, width, label='2015', stacked = True)
rects2 = ax.barh(x = {male_numbers_2018, female_numbers_2018}, x + width/2, width, label='2018', stacked = True)
plt.show()
Here I want to group the bars by the index
variable, for example, the Poorest 10% category will have two bars associated with that label: the 2015 and 2018 figures. Within each bar, I need to stack the male and female figures, for example in the Poorest 10% category: the 2015 bar will comprise the 2015 percentage of females and the 2015 percentage of males that make up that category.
Your help is greatly appreciated!