Plotting
Overview
Teaching: 15 min
Exercises: 20 minQuestions
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.
- Commonly use a sub-library called
matplotlib.pyplot
. - The Jupyter Notebook will render plots inline if we ask it to using a “magic” command.
%matplotlib inline
import matplotlib.pyplot as plt
- Simple plots are then (fairly) simple to create.
time = [0, 1, 2, 3]
position = [0, 100, 200, 300]
plt.plot(time, position)
plt.xlabel('Time (hr)')
plt.ylabel('Position (km)')
Plot data directly from a Pandas dataframe
.
- We can also plot Pandas dataframes.
- This implicitly uses
matplotlib.pyplot
. - Before plotting, we convert the column headings from a
string
tointeger
data type, since they represent numerical values
import pandas
data = pandas.read_csv('data/gapminder_gdp_oceania.csv', index_col='country')
# Extract year from last 4 characters of each column name
years = data.columns.str.strip('GDPPercap_')
# Convert year values to integers, saving results back to dataframe
data.columns = years.astype(int)
data.loc['Australia'].plot()
Select and transform data, then plot it.
- By default,
DataFrame.plot
plots with the rows as the X axis. - We can transpose the data in order to plot multiple series.
data.T.plot()
plt.ylabel('GDP per capita')
Many styles of plot are available.
- For example, do a bar plot using a fancier style.
plt.style.use('ggplot')
data.T.plot(kind='bar')
plt.ylabel('GDP per capita')
Data can also be plotted by calling the matplotlib
plot
function directly.
- The command is
plt.plot(x, y)
- The color / format of markers can also be specified as an optical argument: e.g. ‘b-‘ is a blue line, ‘g–’ is a green dashed line.
Get Australia data from dataframe
years = data.columns
GDP_australia = data.loc['Australia']
plt.plot(years, GDP_australia, 'g--')
Can plot many sets of data together.
# Select two countries' worth of data.
GDP_australia = data.loc['Australia']
GDP_nz = data.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 ($)')
- Plot a scatter plot correlating the GDP of Australia and New Zealand
- Use either
plt.scatter
orDataFrame.plot.scatter
plt.scatter(GDP_australia, GDP_nz)
data.T.plot.scatter(x = 'Australia', y = 'New Zealand')
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.
data_europe = pandas.read_csv('data/gapminder_gdp_europe.csv', index_col='country') data_europe.____.plot(label='min') data_europe.____ plt.legend(loc='best') plt.xticks(rotation=90)
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)?
data_asia = pandas.read_csv('data/gapminder_gdp_asia.csv', index_col='country') data_asia.describe().T.plot(kind='scatter', x='min', y='max')
You might note that the variability in the maximum GDP is much higher than that of the minimum. Take a look at the maximum GDP over time, as well as the min/max indices. What do you find out?data_asia.max().plot() print(data_asia.idxmax()) print(data_asia.idxmin())
More Correlations
This short program creates a plot showing the correlation between GDP and life expectancy for 2007:
data_all = pandas.read_csv('data/gapminder_all.csv', index_col='country') data_all.plot(kind='scatter', x='GDPPercap_2007', y='lifeExp_2007', s=data_all['pop_2007']/1e6)
Using online help and other resources, explain what each argument toplot
does.
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. withplt.show
) matplotlib will make this variable refer to a new empty figure. Therefore, make sure you callplt.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 data.plot(kind='bar') fig.savefig('my_figure.png')
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.