Line chart with Python

Cedric Vidonne

Lei Chen

Line chart with Python

A line chart is a type of chart that displays the evolution of one or several numeric variables over a continuous interval or time period. Typically, the x-axis is used for a timescale or a sequence of intervals, while the y-axis reports values across that progression.

More about: Line chart


Single line chart

# import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
plt.style.use(['unhcrpyplotstyle','line'])

#compute data array for plotting
df = pd.read_csv('https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/change_over_time/line.csv')

df = df.pivot(index='year', columns='population_type', values='population_number')
df = df.reset_index()

#compute data for plotting
x = df['year']
y = df['Refugees']

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

#set chart title
ax.set_title('Number of refugees | 1990-2021')

#set y-axis label
ax.set_ylabel('Number of people (millions)')

#set y-axis limit
ylimit = plt.ylim(8 * 1e6, 22 * 1e6)

#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 > 0:
        s = '{:1.0f}K'.format(x*1e-3)
    else: 
        s = '{:1.0f}'.format(x)
    return s
ax.yaxis.set_major_formatter(number_formatter)

#set chart source and copyright
plt.annotate('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)

#adjust chart margin and layout
fig.tight_layout()

#show chart
plt.show()

A line chart showing number of refugees and IDPs of concern to UNHCR | 1990-2021


Multiple line chart

# import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
plt.style.use(['unhcrpyplotstyle','line'])

#compute data array for plotting
df = pd.read_csv('https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/change_over_time/line.csv')

df = df.pivot(index='year', columns='population_type', values='population_number')
df = df.reset_index()

#compute data for plotting
x = df['year']
y1 = df['IDPs']
y2 = df['Refugees']

#plot the chart
fig, ax = plt.subplots()
bar_plot = ax.plot(x, y1)
bar_plot = ax.plot(x, y2)

#set chart title
ax.set_title('Number of refugees and IDPs of concern to UNHCR | 1990-2021')

#set y-axis label
ax.set_ylabel('Number of people (millions)')

#set y-axis limit
ylimit = plt.ylim(0, 60 * 1e6)

#set direct labeling for lines
idp_xpos=x.iloc[-1]
idp_ypos=y1.iloc[-1]
plt.annotate("IDPs", (idp_xpos,idp_ypos),
                 textcoords="offset points",
                 xytext=(0,10), 
                 ha='center')
ref_xpos=x.iloc[-1]
ref_ypos=y2.iloc[-1]
plt.annotate("Refugees", (ref_xpos,ref_ypos),
                 textcoords="offset points",
                 xytext=(0,10), 
                 ha='left')

#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 > 0:
        s = '{:1.0f}K'.format(x*1e-3)
    else: 
        s = '{:1.0f}'.format(x)
    return s
ax.yaxis.set_major_formatter(number_formatter)

#set chart source and copyright
plt.annotate('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)

#adjust chart margin and layout
fig.tight_layout()

#show chart
plt.show()

A line chart showing number of refugees and IDPs of concern to UNHCR | 1990-2021


Related chart with Python