Plotting and Visualization

#Plotting-and-Visualization

There are a handful of third-party Python packages that are suitable for creating scientific plots and visualizations. These include packages like:

  • matplotlib
  • Chaco
  • PyX
  • Bokeh

Here, we will focus excelusively on matplotlib and the high-level plotting availabel within pandas. It is currently the most robust and feature-rich package available.

Visual representation of data

#Visual-representation-of-data

We require plots, charts and other statistical graphics for the written communication of quantitative ideas.

They allow us to more easily convey relationships and reveal deviations from patterns.

Gelman and Unwin 2011:

A well-designed graph can display more information than a table of the same size, and more information than numbers embedded in text. Graphical displays allow and encourage direct visual comparisons.

Matplotlib

#Matplotlib

The easiest way to interact with matplotlib is via pylab in iPython. By starting iPython (or iPython notebook) in "pylab mode", both matplotlib and numpy are pre-loaded into the iPython session:

1
ipython notebook --pylab

You can specify a custom graphical backend (e.g. qt, gtk, osx), but iPython generally does a good job of auto-selecting. Now matplotlib is ready to go, and you can access the matplotlib API via plt. If you do not start iPython in pylab mode, you can do this manually with the following convention:

1
import matplotlib.pyplot as plt
Loading output library...
Loading output library...

The above plot simply shows two sets of random numbers taken from a normal distribution plotted against one another. The 'ro' argument is a shorthand argument telling matplotlib that I wanted the points represented as red circles.

This plot was expedient. We can exercise a little more control by breaking the plotting into a workflow:

Loading output library...

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.

If you want to make your plots look pretty like mine, steal the matplotlibrc file from Huy Nguyen.

Plotting in Pandas

#Plotting-in-Pandas

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.

Loading output library...
Loading output library...

Notice that by default a line plot is drawn, and a light grid is included. All of this can be changed, however:

Loading output library...
Loading output library...

Similarly, for a DataFrame:

Loading output library...
Loading output library...

As an illustration of the high-level nature of Pandas plots, we can split multiple series into subplots with a single argument for plot:

Loading output library...
Loading output library...

Or, we may want to have some series displayed on the secondary y-axis, which can allow for greater detail and less empty space:

Loading output library...
Loading output library...

If we would like a little more control, we can use matplotlib's subplots function directly, and manually assign plots to its axes:

Loading output library...
Loading output library...

Bar plots

#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:

Loading output library...
Loading output library...
Loading output library...
Loading output library...
Loading output library...
Loading output library...
Loading output library...

Another way of comparing the groups is to look at the survival rate, by adjusting for the number of people in each group.

Loading output library...
Loading output library...

Histograms

#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:

Loading output library...
Loading output library...

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):

Loading output library...
Loading output library...

There are algorithms for determining an "optimal" number of bins, each of which varies somehow with the number of observations in the data series.

Loading output library...
Loading output library...
Loading output library...

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.

Loading output library...
Loading output library...

Often, histograms and density plots are shown together:

Loading output library...
Loading output library...

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

#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.

Loading output library...
Loading output library...

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.

Loading output library...

When data are dense, a couple of tricks used above help the visualization:

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

A related but inferior cousin of the box plot is the so-called dynamite plot, which is just a bar chart with half of an error bar.

Loading output library...
Loading output library...

Why is this plot a poor choice?

  • bar charts should be used for measurable quantities (e.g. raw data), not estimates. The area of the bar does not represent anything, since these are estimates derived from the data.
  • the "data-ink ratio" (sensu Edward Tufte) is very high. There are only 6 values represented here (3 means and 3 standard deviations).
  • the plot hides the underlying data.

A boxplot is always a better choice than a dynamite plot.

Loading output library...
Loading output library...
Loading output library...

Exercise

#Exercise

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

Scatterplots

#Scatterplots

To look at how Pandas does scatterplots, let's reload the baseball sample dataset.

Loading output library...

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.

Loading output library...
Loading output library...

We can add additional information to scatterplots by assigning variables to either the size of the symbols or their colors.

Loading output library...
Loading output library...
Loading output library...

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.

Loading output library...

Trellis Plots

#Trellis-Plots

One of the enduring strengths of carrying out statistical analyses in the R language is the quality of its graphics. In particular, the addition of Hadley Wickham's ggplot2 package allows for flexible yet user-friendly generation of publication-quality plots. Its srength is based on its implementation of a powerful model of graphics, called the Grammar of Graphics (GofG). The GofG is essentially a theory of scientific graphics that allows the components of a graphic to be completely described. ggplot2 uses this description to build the graphic component-wise, by adding various layers.

Pandas recently added functions for generating graphics using a GofG approach. Chiefly, this allows for the easy creation of trellis plots, which are a faceted graphic that shows relationships between two variables, conditioned on particular values of other variables. This allows for the representation of more than two dimensions of information without having to resort to 3-D graphics, etc.

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

  • Create a RPlot object that merely relates two variables in the dataset
  • Add a grid that will be used to condition the variables by both passenger class and sex
  • Add the actual plot that will be used to visualize each comparison
  • Draw the visualization
Loading output library...

Using the cervical dystonia dataset, 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 polynomial relationship between age and twstrs:

Loading output library...
Loading output library...

We can use the RPlot class to represent more than just trellis graphics. It is also useful for displaying multiple variables on the same panel, using combinations of color, size and shapes to do so.

Loading output library...