Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Plotting with Pandas

DS 2023 | Communicating wiht Data

Overview

This notebook provides a gentle introduction to using Pandas’ plotting function.

The main goal is to get you acquainted with how the plot method works in Pandas, not to provide a thorough introduction to all of its syntax and functionality.

Also, you are not expected to remember every detail about how the plot method works — these things will be reintroduced and reinforced in the lessons that follow.

Setting Up

To use Pandas for plotting visualizations, you can just import Pandas as ususal.

There is no special plotting module to install.

However, we often import other libraries since Pandas relies on those under the hood.

The other libraries are:

  • NumPy: for access to more data types and math stuff.

  • Matplotlib (specifically, the PyPlot interface): for better control over plot design.

  • Seaborn: for practice datasets and extra plotting tools.

A first example

To get started with plotting in Pandas, let’s import the fligts dataset from Seaborn.

Loading...

Recall that this dataset has two grouping categores, year and month, and one measurement, passengers.

The grouping columns also form a key, so let’s save that information.

Now, let’s try to create a line graph showing the number of passengers over time.

<Axes: >
<Figure size 640x480 with 1 Axes>

Notice how we just grabbed the column’s name, which returns a series.

Pandas takes the data and plots it as a line graph.

The x axis maps the index and the y axis maps the value of passengers.

We can also tell Pandas explicitly to assign passengers to the y axis.

<Axes: >
<Figure size 640x480 with 1 Axes>

Now, if we wanted to replace the y axis values with year and month, you might think we can pass the two columns to the x argument, but this won’t work.

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[6], line 1
----> 1 flights.plot(x=group_cols, y='passengers')

File /opt/miniconda3/envs/ds2023/lib/python3.12/site-packages/pandas/plotting/_core.py:1150, in PlotAccessor.__call__(self, *args, **kwargs)
   1148         x = data_cols[x]
   1149     elif not isinstance(data[x], ABCSeries):
-> 1150         raise ValueError("x must be a label or position")
   1151     data = data.set_index(x)
   1152 if y is not None:
   1153     # check if we have y as int or list of ints

ValueError: x must be a label or position

Python throws a ValueError because the x argument expects a single value, not a list.

To get around this issue, we could create a new column that combines year and month into a single string and plot that.

<Axes: xlabel='year_month'>
<Figure size 640x480 with 1 Axes>

This works, but it’s cumbersome.

A better idea is to assign our grouping columns to the index.

Pandas will use the index for the x axis if no x value is specified.

Loading...
<Axes: xlabel='year,month'>
<Figure size 640x480 with 1 Axes>

We can see that our axis labels look crowded, so let’s widen the figure by using the figsize argument.

<Axes: xlabel='year,month'>
<Figure size 1000x500 with 1 Axes>

Notice also that every time we use .plot(), Pandas returns a string above the rendered plot:

<Axes: xlabel='year,month'>

This the name of the object that is being returns. We can hide this from showing by following the plot statement with the expression plt.show(). You can of this statement as a directive to PyPlot, which is managing the process of displaying the plot, to show the plot. We’ll learn about what Axes and PyPlot mean later.

<Figure size 1000x500 with 1 Axes>

The line plot we have create shows that the number of flights has increased over time. We also see that it fluctuates on a yearly basis. The behavior is called seasonality.

One way to capture the seasonal structure of the data is to convert the table from tidy to wide form.

As we saw in a previous notebook, we can unstack a table with at least two index columns and a measurement column.

Loading...

Now when we call .plot(), each feature, which is a unique value of the month domain, will be plotted as a separate line.

<Figure size 640x480 with 1 Axes>

A more effective way to represent these data is by transposing the table and then plotting it.

<Figure size 640x480 with 1 Axes>

Here we can see clearly both the seasonality of the data and the yearly increase in the number of passengers.

Now, the above plot looks a bit crowded. To remedy this, we can use the subplots argument to create separate figures for each plot.

<Figure size 640x480 with 12 Axes>

Again, we can adjust the size of the figure to give us some room.

<Figure size 500x2000 with 12 Axes>

Note that the y axis on each of the subplots is different.

That’s because the plotting engine is clipping it to the range of the data it is plotting.

If we wanted all the subplots to have the same y axis scale, we would set sharey=True.

<Figure size 500x2000 with 12 Axes>

Now, let’s say you want to plot the average number of flights per month in the dataset.

To do that, we can compute the mean of all the columns, which returns a series.

month Jan 241.750000 Feb 235.000000 Mar 270.166667 Apr 267.083333 May 271.833333 Jun 311.666667 Jul 351.333333 Aug 351.083333 Sep 302.416667 Oct 266.583333 Nov 232.833333 Dec 261.833333 dtype: float64

And then we can plot the series.

While we are at it, let’s throw in a title to our plot.

<Figure size 640x480 with 1 Axes>

To emphasize that our data are discrete, we can style the plot using dots and lines by using the style argument.

<Figure size 640x480 with 1 Axes>

We could also represent this plot as a bar chart by assigning bar to the kind argument.

<Figure size 640x480 with 1 Axes>

To make the dates read horizontally, we can set rot to 0°0\degree.

<Figure size 640x480 with 1 Axes>

We can also set the kind to a boxplot.

<Figure size 640x480 with 1 Axes>

Summary

Pandas’ plot method assumes that the x axis is the index of the dataframe or series, unless specified by the x argument.

If specified by x, the value can’t be a list of columns.

If no value for y is given, Pandas assumes that you want to plot all the numeric columns.

Each of the plotted columns will be assigned a line.

The plot method has a kind argument to specify other kinds of plot, including bar plots, box plot, and other kinds.

The default plot type is a line graph.

We will review individually all this plots Pandas can make.

For more information

Check out Pandas’ tutorial and documention on its plotting capabilities.