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.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as snsA first example¶
To get started with plotting in Pandas, let’s import the fligts dataset from Seaborn.
flights = sns.load_dataset('flights')
flights.head()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.
group_cols = ['year', 'month']Now, let’s try to create a line graph showing the number of passengers over time.
flights['passengers'].plot()<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.
flights.plot(y='passengers')<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.
flights.plot(x=group_cols, y='passengers')---------------------------------------------------------------------------
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 positionPython 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.
flights['year_month'] = flights['year'].astype('string') + "-" + flights['month'].astype('string')
flights.plot(x='year_month', y='passengers')<Axes: xlabel='year_month'>
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.
flights1 = flights.set_index(group_cols)
flights1flights1.plot()<Axes: xlabel='year,month'>
We can see that our axis labels look crowded, so let’s widen the figure by using the figsize argument.
flights1.plot(figsize=(10,5))<Axes: xlabel='year,month'>
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.
flights1.plot(figsize=(10,5))
plt.show()
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.
flights2 = flights1['passengers'].unstack()
flights2Now when we call .plot(), each feature, which is a unique value of the month domain, will be plotted as a separate line.
flights2.plot()
plt.show()
A more effective way to represent these data is by transposing the table and then plotting it.
flights2.T.plot()
plt.show()
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.
flights2.T.plot(subplots=True)
plt.show()
Again, we can adjust the size of the figure to give us some room.
flights2.T.plot(subplots=True, figsize=(5,20))
plt.show()
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.
flights2.T.plot(subplots=True, figsize=(5,20), sharey=True)
plt.show()
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.
flight_months = flights2.mean()
flight_monthsmonth
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: float64And then we can plot the series.
While we are at it, let’s throw in a title to our plot.
flight_months.plot()
plt.title("Mean Number Passengers per Month from 1949 to 1960")
plt.show()
To emphasize that our data are discrete, we can style the plot using dots and lines by using the style argument.
flight_months.plot(style='o-')
plt.title("Mean Number Passengers per Month from 1949 to 1960")
plt.show()
We could also represent this plot as a bar chart by assigning bar to the kind argument.
flights2.mean().T.plot(kind='bar')
plt.show()
To make the dates read horizontally, we can set rot to .
flights2.mean().T.plot(kind='bar', rot=0)
plt.show()
We can also set the kind to a boxplot.
flights2.plot(kind='box')
plt.show()
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.