Population pyramid with python
A population pyramid consists of two histograms, one for each gender (conventionally, males on the left and females on the right) where the population numbers are shown horizontally (X-axis) and the age vertically (Y-axis). The values can be displayed either as a percentage of the total population or as a raw number.
More about: Population pyramid
Population pyramid
import matplotlib.pyplot as plt
import pandas as pd
'unhcrpyplotstyle','population_pyramid'])
plt.style.use([
#load data set
= pd.read_csv('https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/distribution/population_pyramid.csv')
df
#compute data array for plotting
= df['male'] / -1
x_male = df['female']
x_female = df['ages']
y
#plot the chart
= plt.subplots()
fig, ax = ax.barh(y, x_male)
ax1 = ax.barh(y, x_female)
ax2
=[f'{x*100:,.0f}%' for x in -ax1.datavalues])
ax.bar_label(ax1, labels=[f'{x*100:,.0f}%' for x in ax2.datavalues])
ax.bar_label(ax2, labels
#set chart title
'Demographic of forcibly displaced people | 2020')
ax.set_title(
#set axis label
'Age groups')
ax.set_ylabel('Male / Female')
ax.set_xlabel(
#set chart source and copyright
'Source: UNHCR Refugee Data Finder', (0,0), (0, -25), xycoords='axes fraction', textcoords='offset points', va='top', color = '#666666', fontsize=9)
plt.annotate('©UNHCR, The UN Refugee Agency', (0,0), (0, -35), xycoords='axes fraction', textcoords='offset points', va='top', color = '#666666', fontsize=9)
plt.annotate(
#adjust chart margin and layout
fig.tight_layout()
#show chart
plt.show()