Plotting

Overview

Teaching: 60 min
Exercises: 30 min
Questions
  • How can I plot my data?

  • How can I save my plot for publishing?

Objectives
  • Create a time series plot showing a single data set.

  • Create a scatter plot showing relationship between two data sets.

matplotlib is the most widely used scientific plotting library in Python.

%matplotlib inline
import matplotlib.pyplot as plt
time = [0, 1, 2, 3]
position = [0, 100, 200, 300]

plt.plot(time, position)
plt.xlabel('Time (hr)')
plt.ylabel('Position (km)')

Simple Position-Time Plot

Plot data directly from a Pandas dataframe.

If you don’t have the data files (e.g., using Google Colab), we will want to download them.


# Same download function as last time

import urllib.request
import os

def download_data(filename):
  if not os.path.exists('data'):
          os.mkdir('data')
  url = 'https://raw.githubusercontent.com/ualberta-rcg/python-intro/gh-pages/data/' + filename
  output_file = 'data/' + filename
  urllib.request.urlretrieve(url, output_file)
  print("Downloaded " + filename + " to the data directory")

# Run the function to download

filenames = ['gapminder_gdp_oceania.csv',
             'gapminder_gdp_europe.csv',
             'gapminder_gdp_asia.csv',
             'gapminder_all.csv']

for filename in filenames:
  download_data(filename)
import pandas as pd

oceania_df = pd.read_csv('data/gapminder_gdp_oceania.csv', index_col='country')

# Extract year from last 4 characters of each column name
years = oceania_df.columns.str.strip('gdpPercap_')
# Convert year values to integers, saving results back to dataframe
oceania_df.columns = years.astype(int)

oceania_df.loc['Australia'].plot()

GDP plot for Australia

Select and transform data, then plot it.

oceania_df.T.plot()
plt.ylabel('GDP per capita')

GDP plot for Australia and New Zealand

Many styles of plot are available.

plt.style.use('ggplot')
oceania_df.T.plot(kind='bar')
plt.ylabel('GDP per capita')

GDP barplot for Australia

Data can also be plotted by calling the matplotlib plot function directly.

Get Australia data from dataframe

years = oceania_df.columns
gdp_australia = oceania_df.loc['Australia']

plt.plot(years, gdp_australia, 'g--')

GDP formatted plot for Australia

Can plot many sets of data together.

# Select two countries' worth of data.
gdp_australia = oceania_df.loc['Australia']
gdp_nz = oceania_df.loc['New Zealand']

# Plot with differently-colored markers.
plt.plot(years, gdp_australia, 'b-', label='Australia')
plt.plot(years, gdp_nz, 'g-', label='New Zealand')

# Create legend.
plt.legend(loc='upper left')
plt.xlabel('Year')
plt.ylabel('GDP per capita ($)')

Adding a Legend

Often when plotting multiple datasets on the same figure it is desirable to have a legend describing the data.

This can be done in matplotlib in two stages:

  • Provide a label for each dataset in the figure:
plt.plot(years, gdp_australia, label='Australia')
plt.plot(years, gdp_nz, label='New Zealand')
  • Instruct matplotlib to create the legend.
plt.legend()

By default matplotlib will attempt to place the legend in a suitable position. If you would rather specify a position this can be done with the loc= argument, e.g to place the legend in the upper left corner of the plot, specify loc='upper left'

GDP formatted plot for Australia and New Zealand

plt.scatter(gdp_australia, gdp_nz)

GDP correlation using plt.scatter

oceania_df.T.plot.scatter(x = 'Australia', y = 'New Zealand')

GDP correlation using data.T.plot.scatter

Minima and Maxima

Fill in the blanks below to plot the minimum GDP per capita over time for all the countries in Europe. Modify it again to plot the maximum GDP per capita over time for Europe.

europe_df = pd.read_csv('data/gapminder_gdp_europe.csv', index_col='country')
europe_df.____.plot(label='min')
europe_df.____
plt.legend(loc='best')
plt.xticks(rotation=90)

Solution

europe_df = pd.read_csv('data/gapminder_gdp_europe.csv', index_col='country')
europe_df.min().plot(label='min')
europe_df.max().plot(label='max')
plt.legend(loc='best')
plt.xticks(rotation=90)

Minima Maxima Solution

Correlations

Modify the example in the notes to create a scatter plot showing the relationship between the minimum and maximum GDP per capita among the countries in Asia for each year in the data set. What relationship do you see (if any)?

asia_df = pd.read_csv('data/gapminder_gdp_asia.csv', index_col='country')
asia_df.describe().T.plot(kind='scatter', x='min', y='max')

Solution

Correlations Solution 1

No particular correlations can be seen between the minimum and maximum gdp values year on year. It seems the fortunes of asian countries do not rise and fall together.

You might note that the variability in the maximum is much higher than that of the minimum. Take a look at the maximum and the max indexes:

asia_df = pd.read_csv('data/gapminder_gdp_asia.csv', index_col='country')
asia_df.max().plot()
print(asia_df.idxmax())
print(asia_df.idxmin())

Solution

Correlations Solution 2

Seems the variability in this value is due to a sharp drop after 1972. Some geopolitics at play perhaps? Given the dominance of oil producing countries, maybe the Brent crude index would make an interesting comparison? Whilst Myanmar consistently has the lowest gdp, the highest gdb nation has varied more notably.

More Correlations

This short program creates a plot showing the correlation between GDP and life expectancy for 2007, normalizing marker size by population:

all_df = pd.read_csv('data/gapminder_all.csv', index_col='country')
all_df.plot(kind='scatter', x='gdpPercap_2007', y='lifeExp_2007',
            s=all_df['pop_2007']/1e6)

Using online help and other resources, explain what each argument to plot does.

Solution

More Correlations Solution

A good place to look is the documentation for the plot function - help(data_all.plot).

kind - As seen already this determines the kind of plot to be drawn.

x and y - A column name or index that determines what data will be placed on the x and y axes of the plot

s - Details for this can be found in the documentation of plt.scatter. A single number or one value for each data point. Determines the size of the plotted points.

Saving your plot to a file

If you are satisfied with the plot you see you may want to save it to a file, perhaps to include it in a publication. There is a function in the matplotlib.pyplot module that accomplishes this: savefig. Calling this function, e.g. with

plt.savefig('my_figure.png')

will save the current figure to the file my_figure.png. The file format will automatically be deduced from the file name extension (other formats are pdf, ps, eps and svg).

Note that functions in plt refer to a global figure variable and after a figure has been displayed to the screen (e.g. with plt.show) matplotlib will make this variable refer to a new empty figure. Therefore, make sure you call plt.savefig before the plot is displayed to the screen, otherwise you may find a file with an empty plot.

When using dataframes, data is often generated and plotted to screen in one line, and plt.savefig seems not to be a possible approach. One possibility to save the figure to file is then to

  • save a reference to the current figure in a local variable (with plt.gcf)
  • call the savefig class method from that varible.
fig = plt.gcf() # get current figure
europe_df.plot(kind='bar')
fig.savefig('my_figure.png')

Making your plots accessible

Whenever you are generating plots to go into a paper or a presentation, there are a few things you can do to make sure that everyone can understand your plots.

  • Always make sure your text is large enough to read. Use the fontsize parameter in xlabel, ylabel, title, and legend, and tick_params with labelsize to increase the text size of the numbers on your axes.
  • Similarly, you should make your graph elements easy to see. Use s to increase the size of your scatterplot markers and linewidth to increase the sizes of your plot lines.
  • Using color (and nothing else) to distinguish between different plot elements will make your plots unreadable to anyone who is colorblind, or who happens to have a black-and-white office printer. For lines, the linestyle parameter lets you use different types of lines. For scatterplots, marker lets you change the shape of your points. If you’re unsure about your colors, you can use Coblis or Color Oracle to simulate what your plots would look like to those with colorblindness.

Key Points

  • matplotlib is the most widely used scientific plotting library in Python.

  • Plot data directly from a Pandas dataframe.

  • Select and transform data, then plot it.

  • Many styles of plot are available: see the Python Graph Gallery for more options.

  • Can plot many sets of data together.