Column chart with Python
In a column chart, each category is represented by a vertical rectangle, with the height of the rectangle being proportional to the values being plotted.
More about: Column chart
Basic column chart
# import libraries
import matplotlib.pyplot as plt
import pandas as pd
'unhcrpyplotstyle','column'])
plt.style.use([
#load data set
= pd.read_csv('https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/comparison/column.csv')
df
#compute data array for plotting
= df['year']
x = df['displaced_number']
y
#plot the chart
= plt.subplots()
fig, ax = ax.bar(x, y)
bar_plot
#set chart title
'Global IDP displacement | 2010 - 2020')
ax.set_title(
#set y-axis title
'Displaced population (millions)')
ax.set_ylabel(
#set y-axis labels
=True)
ax.tick_params(labelleft
#set y-axis limit
= plt.ylim(0, 100*1e6)
ylimit
#set tick based on x value
ax.set_xticks(x)
#set grid
='y')
ax.grid(axis
#format y-axis tick labels
def number_formatter(x, pos):
if x >= 1e6:
= '{:1.0f}M'.format(x*1e-6)
s elif x < 1e6 and x >= 1e3:
= '{:1.0f}K'.format(x*1e-3)
s else:
= '{:1.0f}'.format(x)
s return s
ax.yaxis.set_major_formatter(number_formatter)
#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()
Column chart with data label
# import libraries
import matplotlib.pyplot as plt
import pandas as pd
'unhcrpyplotstyle','column'])
plt.style.use([
#load data set
= pd.read_csv('https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/comparison/column.csv')
df
#compute data array for plotting
= df['year']
x = df['displaced_number']
y
#plot the chart
= plt.subplots()
fig, ax = ax.bar(x, y)
bar_plot
#set chart title
'Global IDP displacement | 2010 - 2020')
ax.set_title(
#set subtitle
'Number of people in millions', x=0.025, y=0.88, ha='left')
plt.suptitle(
#set tick based on x value
ax.set_xticks(x)
# set formatted data label
for x,y in zip(x,y):
= "{:.1f}".format(y*1e-6)
label
plt.annotate(label,
(x,y),="offset points",
textcoords=(0,6),
xytext='center')
ha
#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()