High-level Plotting with Pandas and Seaborn

In 2016, there are more options for generating plots in Python than ever before:

  • matplotlib
  • Pandas
  • Seaborn
  • ggplot
  • Bokeh
  • pygal
  • Plotly

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.


In [ ]:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

In [ ]:
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:


In [ ]:
normals.cumsum().plot(grid=True)

Similarly, for a DataFrame:


In [ ]:
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:


In [ ]:
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:


In [ ]:
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:


In [ ]:
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

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:


In [ ]:
titanic = pd.read_excel("../data/titanic.xls", "titanic")
titanic.head()

In [ ]:
titanic.groupby('pclass').survived.sum().plot.bar()

In [ ]:
titanic.groupby(['sex','pclass']).survived.sum().plot.barh()

In [ ]:
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.


In [ ]:
death_counts.div(death_counts.sum(1).astype(float), axis=0).plot.barh(stacked=True, color=['black','gold'])

Histograms

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:


In [ ]:
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):


In [ ]:
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.


In [ ]:
sturges = lambda n: int(np.log2(n) + 1)
square_root = lambda n: int(np.sqrt(n))
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)
sturges(n), square_root(n), doanes(titanic.fare.dropna())

In [ ]:
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.


In [ ]:
titanic.fare.dropna().plot.kde(xlim=(0,600))

Often, histograms and density plots are shown together:


In [ ]:
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.

Boxplots

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.


In [ ]:
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.


In [ ]:
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:

  1. reducing the alpha level to make the points partially transparent
  2. adding random "jitter" along the x-axis to avoid overstriking

Exercise

Using the Titanic data, create kernel density estimate plots of the age distributions of survivors and victims.


In [ ]:
# Write your answer here

Scatterplots

To look at how Pandas does scatterplots, let's look at a small dataset in wine chemistry.


In [ ]:
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.


In [ ]:
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.


In [ ]:
wine.plot.scatter('Color intensity', 'Hue', s=wine.Alcohol*100, alpha=0.5)

In [ ]:
wine.plot.scatter('Color intensity', 'Hue', c=wine.Grape)

In [ ]:
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.


In [ ]:
_ = pd.scatter_matrix(wine.loc[:, 'Alcohol':'Flavanoids'], figsize=(14,14), diagonal='kde')

Seaborn

Seaborn is a modern data visualization tool for Python, created by Michael Waskom. Seaborn's high-level interface makes it easy to visually explore your data, by being able to easily iterate through different plot types and layouts with minimal hand-coding. In this way, Seaborn complements matplotlib (which we will learn about later) in the data science toolbox.

An easy way to see how Seaborn can immediately improve your data visualization, is by setting the plot style using one of its sevefral built-in styles.

Here is a simple pandas plot before Seaborn:


In [ ]:
normals.plot()

Seaborn is conventionally imported using the sns alias. Simply importing Seaborn invokes the default Seaborn settings. These are generally more muted colors with a light gray background and subtle white grid lines.


In [ ]:
import seaborn as sns

normals.plot()

Customizing Seaborn Figure Aesthetics

Seaborn manages plotting parameters in two general groups:

  • setting components of aesthetic style of the plot
  • scaling elements of the figure

This default theme is called darkgrid; there are a handful of preset themes:

  • darkgrid
  • whitegrid
  • dark
  • white
  • ticks

Each are suited to partiular applications. For example, in more "data-heavy" situations, one might want a lighter background.

We can apply an alternate theme using set_style:


In [ ]:
sns.set_style('whitegrid')
sns.boxplot(x='pclass', y='age', data=titanic)

In [ ]:
sns.set_style('ticks')
sns.boxplot(x='pclass', y='age', data=titanic)

The figure still looks heavy, with the axes distracting from the lines in the boxplot. We can remove them with despine:


In [ ]:
sns.boxplot(x='pclass', y='age', data=titanic)
sns.despine()

Finally, we can give the plot yet more space by specifying arguments to despine; specifically, we can move axes away from the figure elements (via offset) and minimize the length of the axes to the lowest and highest major tick value (via trim):


In [ ]:
sns.boxplot(x='pclass', y='age', data=titanic)
sns.despine(offset=20, trim=True)

The second set of figure aesthetic parameters controls the scale of the plot elements.

There are four default scales that correspond to different contexts that a plot may be intended for use with.

  • paper
  • notebook
  • talk
  • poster

The default is notebook, which is optimized for use in Jupyter notebooks. We can change the scaling with set_context:


In [ ]:
sns.set_context('paper')

sns.boxplot(x='pclass', y='age', data=titanic)
sns.despine(offset=20, trim=True)

In [ ]:
sns.set_context('poster')

sns.boxplot(x='pclass', y='age', data=titanic)
sns.despine(offset=20, trim=True)

Each of the contexts can be fine-tuned for more specific applications:


In [ ]:
sns.set_context('notebook', font_scale=0.5, rc={'lines.linewidth': 0.5})

sns.boxplot(x='pclass', y='age', data=titanic)
sns.despine(offset=20, trim=True)

The detailed settings are available in the plotting.context:


In [ ]:
sns.plotting_context()

Seaborn works hand-in-hand with pandas to create publication-quality visualizations quickly and easily from DataFrame and Series data.

For example, we can generate kernel density estimates of two sets of simulated data, via the kdeplot function.


In [ ]:
data = np.random.multivariate_normal([0, 0], [[5, 2], [2, 2]], size=2000)
data = pd.DataFrame(data, columns=['x', 'y'])
data.head()

In [ ]:
sns.set()

for col in 'xy':
    sns.kdeplot(data[col], shade=True)

distplot combines a kernel density estimate and a histogram.


In [ ]:
sns.distplot(data['x'])

If kdeplot is provided with two columns of data, it will automatically generate a contour plot of the joint KDE.


In [ ]:
sns.kdeplot(data);

In [ ]:
cmap = {1:'Reds', 2:'Blues', 3:'Greens'}

for grape in cmap:
    alcohol, phenols = wine.loc[wine.Grape==grape, ['Alcohol', 'Total phenols']].T.values
    
    sns.kdeplot(alcohol, phenols,
        cmap=cmap[grape], shade=True, shade_lowest=False, alpha=0.3)

Similarly, jointplot will generate a shaded joint KDE, along with the marginal KDEs of the two variables.


In [ ]:
with sns.axes_style('white'):
    sns.jointplot("Alcohol", "Total phenols", wine, kind='kde');

Notice in the above, we used a context manager to temporarily assign a white axis stype to the plot. This is a great way of changing the defaults for just one figure, without having to set and then reset preferences.

You can do this with a number of the seaborn defaults. Here is a dictionary of the style settings:


In [ ]:
sns.axes_style()

In [ ]:
with sns.axes_style('white', {'font.family': ['serif']}):
    sns.jointplot("Alcohol", "Total phenols", wine, kind='kde');

To explore correlations among several variables, the pairplot function generates pairwise plots, along with histograms along the diagonal, and a fair bit of customization.


In [ ]:
titanic = titanic[titanic.age.notnull() & titanic.fare.notnull()]

In [ ]:
sns.pairplot(titanic, vars=['age', 'fare', 'pclass', 'sibsp'], hue='survived', palette="muted", markers='+')

Plotting Small Multiples on Data-aware Grids

The pairplot above is an example of replicating the same visualization on different subsets of a particular dataset. This facilitates easy visual comparisons among groups, making otherwise-hidden patterns in complex data more apparent.

Seaborn affords a flexible means for generating plots on "data-aware grids", provided that your pandas DataFrame is structured appropriately. In particular, you need to organize your variables into columns and your observations (replicates) into rows. Using this baseline pattern of organization, you can take advantage of Seaborn's functions for easily creating lattice plots from your dataset.

FacetGrid is a Seaborn object for plotting mutliple variables simulaneously as trellis plots. Variables can be assigned to one of three dimensions of the FacetGrid:

  • rows
  • columns
  • colors (hue)

Let's use the titanic dataset to create a trellis plot that represents 3 variables at a time. This consists of 2 steps:

  1. Create a FacetGrid object that relates two variables in the dataset in a grid of pairwise comparisons.
  2. Add the actual plot (distplot) that will be used to visualize each comparison.

The first step creates a set of axes, according to the dimensions passed as row and col. These axes are empty, however:


In [ ]:
sns.FacetGrid(titanic, col="sex", row="pclass")

The FacetGrid's map method then allows a third variable to be plotted in each grid cell, according to the plot type passed. For example, a distplot will generate both a histogram and kernel density estimate for age, according each combination of sex and passenger class as follows:


In [ ]:
g = sns.FacetGrid(titanic, col="sex", row="pclass")
g.map(sns.distplot, 'age')

To more fully explore trellis plots in Seaborn, we will use a biomedical dataset. These data are from a multicenter, randomized controlled trial of botulinum toxin type B (BotB) in patients with cervical dystonia from nine U.S. sites.

  • Randomized to placebo (N=36), 5000 units of BotB (N=36), 10,000 units of BotB (N=37)
  • Response variable: total score on Toronto Western Spasmodic Torticollis Rating Scale (TWSTRS), measuring severity, pain, and disability of cervical dystonia (high scores mean more impairment)
  • TWSTRS measured at baseline (week 0) and weeks 2, 4, 8, 12, 16 after treatment began

In [ ]:
cdystonia = pd.read_csv('../data/cdystonia.csv')
cdystonia.head()

Notice that this data represents time series of individual patients, comprised of follow-up measurements at 2-4 week intervals following treatment.

As a first pass, we may wish to see how the trajectories of outcomes vary from patient to patient. Using pointplot, we can create a grid of plots to represent the time series for each patient. Let's just look at the first 12 patients:


In [ ]:
g = sns.FacetGrid(cdystonia[cdystonia.patient<=12], col='patient', col_wrap=4)
g.map(sns.pointplot, 'week', 'twstrs', color='0.5')

Where pointplot is particularly useful is in representing the central tendency and variance of multiple replicate measurements. Having examined individual responses to treatment, we may now want to look at the average response among treatment groups. Where there are mutluple outcomes (y variable) for each predictor (x variable), pointplot will plot the mean, and calculate the 95% confidence interval for the mean, using bootstrapping:


In [ ]:
ordered_treat = ['Placebo', '5000U', '10000U']
g = sns.FacetGrid(cdystonia, col='treat', col_order=ordered_treat)
g.map(sns.pointplot, 'week', 'twstrs', color='0.5')

Notice that to enforce the desired order of the facets (lowest to highest treatment level), the labels were passed as a col_order argument to FacetGrid.

Let's revisit the distplot function to look at how the disribution of the outcome variables vary by time and treatment. Instead of a histogram, however, we will here include the "rug", which are just the locations of individual data points that were used to fit the kernel density estimate.


In [ ]:
g = sns.FacetGrid(cdystonia, row='treat', col='week')
g.map(sns.distplot, 'twstrs', hist=False, rug=True)

displot can also fit parametric data models (instead of a kde). For example, we may wish to fit the data to normal distributions. We can used the distributions included in the SciPy package; Seaborn knows how to use these distributions to generate a fit to the data.


In [ ]:
from scipy.stats import norm

g = sns.FacetGrid(cdystonia, row='treat', col='week')
g.map(sns.distplot, 'twstrs', kde=False, fit=norm)

We can take the statistical analysis a step further, by using regplot to conduct regression analyses.

For example, we can simultaneously examine the relationship between age and the primary outcome variable as a function of both the treatment received and the week of the treatment by creating a scatterplot of the data, and fitting a linear relationship between age and twstrs:


In [ ]:
g = sns.FacetGrid(cdystonia, col='treat', row='week')
g.map(sns.regplot, 'age', 'twstrs')

Exercise

From the AIS subdirectory of the data directory, import both the vessel_information table and transit_segments table and join them. Use the resulting table to create a faceted scatterplot of segment length (seg_length) and average speed (avg_sog) as a trellis plot by flag and vessel type.

To simplify the plot, first generate a subset of the data that includes only the 5 most commont ship types and the 5 most common countries.


In [ ]:
segments = pd.read_csv('../data/AIS/transit_segments.csv')
segments.head()

References

Waskom, M. Seaborn Tutorial

VanderPlas, J. Data visualization with Seaborn, O'Reilly.