In 2016, there are more options for generating plots in Python than ever before:
These packages vary with respect to their APIs, output formats, and complexity. A package like matplotlib, while powerful, is a relatively low-level plotting package, that makes very few assumptions about what constitutes good layout (by design), but has a lot of flexiblility to allow the user to completely customize the look of the output.
On the other hand, Seaborn and Pandas include methods for DataFrame and Series objects that are relatively high-level, and that make reasonable assumptions about how the plot should look. This allows users to generate publication-quality visualizations in a relatively automated way.
Matplotlib is an excellent 2D and 3D graphics library for generating scientific figures in Python. Some of the many advantages of this library includes:
One of the of the key features of matplotlib that I would like to emphasize, and that I think makes matplotlib highly suitable for generating figures for scientific publications is that all aspects of the figure can be controlled programmatically. This is important for reproducibility, convenient when one need to regenerate the figure with updated data or changes its appearance.
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
rain = pd.read_table('../data/nashville_precip.txt', delimiter='\s+', na_values='NA', index_col=0)
rain.head()
x = rain.index.values
y = rain['Jan'].values
plt.figure()
plt.plot(x, y, 'r')
plt.xlabel('Year')
plt.ylabel('Rainfall')
plt.title('January rainfall in Nashville')
It is straightforward to customize plotting symbols and create subplots.
plt.figure(figsize=(14,6))
plt.subplot(1,2,1)
plt.plot(x, y, 'r--')
plt.subplot(1,2,2)
plt.plot(x, rain['Feb'], 'g*-')
While the MATLAB-like API is easy and convenient, it is worth learning matplotlib's object-oriented plotting API. It is remarkably powerful and for advanced figures, with subplots, insets and other components it is very nice to work with.
The main idea with object-oriented programming is to have objects with associated methods and functions that operate on them, and no object or program states should be global.
To use the object-oriented API we start out very much like in the previous example, but instead of creating a new global figure instance we store a reference to the newly created figure instance in the fig
variable, and from it we create a new axis instance axes
using the add_axes
method in the Figure
class instance fig
.
fig = plt.figure()
# left, bottom, width, height (range 0 to 1)
# as fractions of figure size
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes.plot(x, y, 'r')
axes.set_xlabel('Year')
axes.set_ylabel('Rainfall')
axes.set_title('January rainfall in Nashville');
Although a little bit more code is involved, the advantage is that we now have full control of where the plot axes are place, and we can easily add more than one axis to the figure.
fig = plt.figure()
axes1 = fig.add_axes([0.1, 0.1, 0.9, 0.9]) # main axes
axes2 = fig.add_axes([0.65, 0.65, 0.3, 0.3]) # inset axes
# main figure
axes1.plot(x, y, 'r')
axes1.set_xlabel('Year')
axes1.set_ylabel('Rainfall')
axes1.set_title('January rainfall in Nashville');
# insert
axes2.plot(x, np.log(y), 'g')
axes2.set_title('Log rainfall');
If we don't care to be explicit about where our plot axes are placed in the figure canvas, then we can use one of the many axis layout managers in matplotlib, such as subplots
.
fig, axes = plt.subplots(nrows=4, ncols=1)
months = rain.columns
for i,ax in enumerate(axes):
ax.plot(x, rain[months[i]], 'r')
ax.set_xlabel('Year')
ax.set_ylabel('Rainfall')
ax.set_title(months[i])
That was easy, but it's not so pretty with overlapping figure axes and labels, right?
We can deal with that by using the fig.tight_layout
method, which automatically adjusts the positions of the axes on the figure canvas so that there is no overlapping content:
fig, axes = plt.subplots(nrows=4, ncols=1, figsize=(10,10))
for i,ax in enumerate(axes):
ax.plot(x, rain[months[i]], 'r')
ax.set_xlabel('Year')
ax.set_ylabel('Rainfall')
ax.set_title(months[i])
fig.tight_layout()
Matplotlib allows the aspect ratio, DPI and figure size to be specified when the Figure
object is created, using the figsize
and dpi
keyword arguments. figsize
is a tuple with width and height of the figure in inches, and dpi
is the dot-per-inch (pixel per inch). To create a figure with size 800 by 400 pixels we can do:
fig = plt.figure(figsize=(8,4), dpi=100)
The same arguments can also be passed to layout managers, such as the subplots
function.
fig, axes = plt.subplots(figsize=(12,3))
axes.plot(x, y, 'r')
axes.set_xlabel('Year')
axes.set_ylabel('Rainfall')
Legends can also be added to identify labelled data.
fig, ax = plt.subplots(figsize=(12,3))
ax.plot(x, rain['Jan'], label="Jan")
ax.plot(x, rain['Aug'], label="Aug")
ax.set_xlabel('Year')
ax.set_ylabel('Rainfall')
ax.legend(loc=1); # upper left corner
Visualizations can be fine tuned in maplotlib, using the attibutes of the figure and axes.
fig = plt.figure(figsize=(3.54, 3.2))
ax = fig.add_subplot(111)
muy = [0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.52,0.54]
sx = [5.668743677,9.254533132,14.23590137,11.87910853,14.6118157,16.8120231,18.58892361,100.1652558,443.4712272]
er = [0.986042277,1.328704279,0.913025089,0.997960015,1.921483929,4.435,2.817,0,0]
gensub = np.arange(0, 25, 0.1)
mon = [0.2386*np.log(i)-0.3751 for i in gensub]
fig.subplots_adjust(left=0.19, bottom=0.16, right=0.91)
ax.set_ylabel("$\mu$ (h$^{-1}$)")
ax.set_xlabel("S ($\mu$M)")
ax.set_xticks(np.arange(5, 23, 2))
ax.set_xlim(4.5, 21.5)
ax.set_yticks(np.arange(0.1, 0.5, 0.1))
ax.set_ylim(0, 0.5)
ax.errorbar(sx, muy, xerr=er, barsabove=True, ls="none", marker="o", mfc="w", color="k")
ax.plot(gensub, mon, ls="dotted", marker="None", mfc="k", color="k")
matplotlib is a relatively low-level plotting package, relative to others. It makes very few assumptions about what constitutes good layout (by design), but has a lot of flexiblility to allow the user to completely customize the look of the output.
On the other hand, Pandas includes methods for DataFrame and Series objects that are relatively high-level, and that make reasonable assumptions about how the plot should look.
normals = pd.Series(np.random.normal(size=10))
normals.plot()
Notice that by default a line plot is drawn, and light background is included. These decisions were made on your behalf by pandas.
All of this can be changed, however:
normals.cumsum().plot(grid=True)
Similarly, for a DataFrame:
variables = pd.DataFrame({'normal': np.random.normal(size=100),
'gamma': np.random.gamma(1, size=100),
'poisson': np.random.poisson(size=100)})
variables.cumsum(0).plot()
As an illustration of the high-level nature of Pandas plots, we can split multiple series into subplots with a single argument for plot
:
variables.cumsum(0).plot(subplots=True, grid=True)
Or, we may want to have some series displayed on the secondary y-axis, which can allow for greater detail and less empty space:
variables.cumsum(0).plot(secondary_y='normal', grid=True)
If we would like a little more control, we can use matplotlib's subplots
function directly, and manually assign plots to its axes:
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 4))
for i,var in enumerate(['normal','gamma','poisson']):
variables[var].cumsum(0).plot(ax=axes[i], title=var)
axes[0].set_ylabel('cumulative sum')
Bar plots are useful for displaying and comparing measurable quantities, such as counts or volumes. In Pandas, we just use the plot
method with a kind='bar'
argument.
For this series of examples, let's load up the Titanic dataset:
titanic = pd.read_excel("../data/titanic.xls", "titanic")
titanic.head()
titanic.groupby('pclass').survived.sum().plot.bar()
titanic.groupby(['sex','pclass']).survived.sum().plot.barh()
death_counts = pd.crosstab([titanic.pclass, titanic.sex], titanic.survived.astype(bool))
death_counts.plot.bar(stacked=True, color=['black','gold'], grid=True)
Another way of comparing the groups is to look at the survival rate, by adjusting for the number of people in each group.
death_counts.div(death_counts.sum(1).astype(float), axis=0).plot.barh(stacked=True, color=['black','gold'])
Frequenfly it is useful to look at the distribution of data before you analyze it. Histograms are a sort of bar graph that displays relative frequencies of data values; hence, the y-axis is always some measure of frequency. This can either be raw counts of values or scaled proportions.
For example, we might want to see how the fares were distributed aboard the titanic:
titanic.fare.hist(grid=False)
The hist
method puts the continuous fare values into bins, trying to make a sensible décision about how many bins to use (or equivalently, how wide the bins are). We can override the default value (10):
titanic.fare.hist(bins=30)
There are algorithms for determining an "optimal" number of bins, each of which varies somehow with the number of observations in the data series.
from scipy.stats import kurtosis
doanes = lambda data: int(1 + np.log(len(data)) + np.log(1 + kurtosis(data) * (len(data) / 6.) ** 0.5))
n = len(titanic)
doanes(titanic.fare.dropna())
titanic.fare.hist(bins=doanes(titanic.fare.dropna()))
A density plot is similar to a histogram in that it describes the distribution of the underlying data, but rather than being a pure empirical representation, it is an estimate of the underlying "true" distribution. As a result, it is smoothed into a continuous line plot. We create them in Pandas using the plot
method with kind='kde'
, where kde
stands for kernel density estimate.
titanic.fare.dropna().plot.kde(xlim=(0,600))
Often, histograms and density plots are shown together:
titanic.fare.hist(bins=doanes(titanic.fare.dropna()), normed=True, color='lightseagreen')
titanic.fare.dropna().plot.kde(xlim=(0,600), style='r--')
Here, we had to normalize the histogram (normed=True
), since the kernel density is normalized by definition (it is a probability distribution).
We will explore kernel density estimates more in the next section.
A different way of visualizing the distribution of data is the boxplot, which is a display of common quantiles; these are typically the quartiles and the lower and upper 5 percent values.
titanic.boxplot(column='fare', by='pclass', grid=False)
You can think of the box plot as viewing the distribution from above. The blue crosses are "outlier" points that occur outside the extreme quantiles.
One way to add additional information to a boxplot is to overlay the actual data; this is generally most suitable with small- or moderate-sized data series.
bp = titanic.boxplot(column='age', by='pclass', grid=False)
for i in [1,2,3]:
y = titanic.age[titanic.pclass==i].dropna()
# Add some random "jitter" to the x-axis
x = np.random.normal(i, 0.04, size=len(y))
plt.plot(x, y.values, 'r.', alpha=0.2)
When data are dense, a couple of tricks used above help the visualization:
Using the Titanic data, create kernel density estimate plots of the age distributions of survivors and victims.
# Write your answer here
To look at how Pandas does scatterplots, let's look at a small dataset in wine chemistry.
wine = pd.read_table("../data/wine.dat", sep='\s+')
attributes = ['Grape',
'Alcohol',
'Malic acid',
'Ash',
'Alcalinity of ash',
'Magnesium',
'Total phenols',
'Flavanoids',
'Nonflavanoid phenols',
'Proanthocyanins',
'Color intensity',
'Hue',
'OD280/OD315 of diluted wines',
'Proline']
wine.columns = attributes
Scatterplots are useful for data exploration, where we seek to uncover relationships among variables. There are no scatterplot methods for Series or DataFrame objects; we must instead use the matplotlib function scatter
.
wine.plot.scatter('Color intensity', 'Hue')
We can add additional information to scatterplots by assigning variables to either the size of the symbols or their colors.
wine.plot.scatter('Color intensity', 'Hue', s=wine.Alcohol*100, alpha=0.5)
wine.plot.scatter('Color intensity', 'Hue', c=wine.Grape)
wine.plot.scatter('Color intensity', 'Hue', c=wine.Alcohol*100, cmap='hot')
To view scatterplots of a large numbers of variables simultaneously, we can use the scatter_matrix
function that was recently added to Pandas. It generates a matrix of pair-wise scatterplots, optiorally with histograms or kernel density estimates on the diagonal.
_ = pd.scatter_matrix(wine.loc[:, 'Alcohol':'Flavanoids'], figsize=(14,14), diagonal='kde')