0

enter image description here

I want to draw a similar horizontal bar chart like this, but there is some errors in my graph.

I tried to draw the bar chart with:

grouped_region =primary_v1.groupby(\['Region', 'Income Group'\])\['Countries and areas'\].count()
grouped_region_pct = grouped_region.groupby(level=0).apply(lambda x: 100 \* x / float(x.sum()))

fig, ax = plt.subplots(figsize=(10, 6))
grouped_region_pct.unstack().plot(kind='barh', stacked=True, ax=ax)

for i, v in enumerate(grouped_region_pct.unstack().values):
for j, k in enumerate(v):
ax.text(k / 2, i, str(round(k, 1)) + '%', ha='center', va='center')

ax.set_xlabel('Percentage')
ax.set_ylabel('Region')
ax.set_title('Composition of Income Group by Region')

However, the % figures are not in the center of the bar, and I also want to add the number of countries for each region at the end of each bar (the no. of countries for each region is different, some has 36, some has 6 only). How can I fix it? Thanks!!

enter image description here

libraG
  • 1
  • 2
  • If you are on the latest version (3.4.2 or later), have you tried [bar_label](https://stackoverflow.com/questions/21397549/horizontal-stacked-bar-plot-and-add-labels-to-each-section) ? If you are on an older version of matplotlib, pls share data for `grouped_region_pct` in text format – Redox Apr 12 '23 at 05:35

0 Answers0