Bar chart with Python

Cedric Vidonne

Lei Chen

Bar chart with Python

A bar chart is a chart in which each category is represented by a horizontal rectangle, with the length of the rectangle proportional to the values being plotted. The horizontal axis shows data value, and the vertical axis displays the categories being compared.

More about: Bar chart


Basic bar chart

# import libraries
import matplotlib.pyplot as plt
import pandas as pd
from textwrap import wrap
plt.style.use(['unhcrpyplotstyle','bar'])

#load data set
df = pd.read_csv('https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/comparison/bar.csv')

#sort value in descending order
df.sort_values('displaced_number',inplace=True)

#prepare data array for plotting
x = df['country_origin']
y = df['displaced_number']

#wrap long labels
x = [ '\n'.join(wrap(l, 20)) for l in x ]

#plot the chart
fig, ax = plt.subplots()
bar_plot = ax.barh(x, y)

#set chart title
ax.set_title('People displaced across borders by country of origin | 2020')

#set x-axis title
ax.set_xlabel('Displaced population (millions)')

#set x-axis label
ax.tick_params(labelbottom=True)

#set x-axis limit
xlimit = plt.xlim(0, 7000000)

#show grid below the bars
ax.grid(axis='x')

#format x-axis tick labels
def number_formatter(x, pos):
    if x >= 1e6:
        s = '{:1.0f}M'.format(x*1e-6)
    elif x < 1e6 and x >= 1e3:
        s = '{:1.0f}K'.format(x*1e-3)
    else: 
        s = '{:1.0f}'.format(x)
    return s
ax.xaxis.set_major_formatter(number_formatter)

#set chart source and copyright
plt.annotate('Source: UNHCR Refugee Data Finder', (0,0), (0, -40), xycoords='axes fraction', textcoords='offset points', va='top', color = '#666666', fontsize=9)
plt.annotate('©UNHCR, The UN Refugee Agency', (0,0), (0, -50), xycoords='axes fraction', textcoords='offset points', va='top', color = '#666666', fontsize=9)

#adjust chart margin and layout
fig.tight_layout()

#show chart
plt.show()

A bar chart showing people displaced across borders by country of origin | 2020


Bar chart with data label

# import libraries
import matplotlib.pyplot as plt
import pandas as pd
from textwrap import wrap
plt.style.use(['unhcrpyplotstyle','bar'])

#load data set
df = pd.read_csv('https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/comparison/bar.csv')

#sort value in descending order
df.sort_values('displaced_number', inplace=True)

#prepare data array for plotting
x = df['country_origin']
y = df['displaced_number']

#wrap long labels
x = [ '\n'.join(wrap(l, 20)) for l in x ]

#plot the chart
fig, ax = plt.subplots()
bar_plot = ax.barh(x, y)

#set chart title
ax.set_title('People displaced across borders by country of origin | 2020')

#set subtitle
plt.suptitle('Number of people in millions', x=0.36, y=0.88)

# set formatted data label
ax.bar_label(bar_plot, labels=[f'{x*1e-6:,.1f}' for x in bar_plot.datavalues], padding=3)

#set chart source and copyright
plt.annotate('Source: UNHCR Refugee Data Finder', (0,0), (0, -5), xycoords='axes fraction', textcoords='offset points', va='top', color = '#666666', fontsize=9)
plt.annotate('© UNHCR, The UN Refugee Agency', (0,0), (0, -15), xycoords='axes fraction', textcoords='offset points', va='top', color = '#666666', fontsize=9)

#adjust chart margin and layout
fig.tight_layout()

#show charts
plt.show()

A bar chart showing people displaced across borders by country of origin | 2020


Related chart with Python