#341 Python Gapminder Animation

The TED talk of Hans Rosling on ‘Developing Country’ is probably one of the most famous dataviz ever. It shows the evolution of life Expectancy and GDP per capita of several countries through an animation. (Data found in the gapminder R library). Here is a reproduction of this work using python, matplotlib and Image magick! Code is commented and thus (I hope) self explanatory.

# libraries
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd

# Get the data (csv file is hosted on the web)
url = 'https://python-graph-gallery.com/wp-content/uploads/gapminderData.csv'
data = pd.read_csv(url)

# And I need to transform my categorical column (continent) in a numerical value group1->1, group2->2...

# For each year:
for i in data.year.unique():

# initialize a figure
fig = plt.figure(figsize=(680/my_dpi, 480/my_dpi), dpi=my_dpi)

# Change color with c and alpha. I map the color to the X axis value.
tmp=data[ data.year == i ]
plt.scatter(tmp['lifeExp'], tmp['gdpPercap'] , s=tmp['pop']/200000 , c=tmp['continent'].cat.codes, cmap="Accent", alpha=0.6, edgecolors="white", linewidth=2)

# Add titles (main and on axis)
plt.xlabel("Life Expectancy")
plt.ylabel("GDP per Capita")
plt.title("Year: "+str(i) )
plt.xlim(30, 90)

# Save it
plt.savefig(filename, dpi=96)

Transformation in a GIF using Image Magick

# Then use image magick (this is bash, not python)
convert -delay 80 Gapminder*.png animated_gapminder.gif

  • Sponsors

  • 1 comment

    Leave a Reply

    Your email address will not be published.