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.

Line Graphs

DS 2023 | Communicating with Data

line-graph.png

Overview

Bar charts show measurement variables associated with the domains of group variables.

Pie charts show measurement variables associated with the domains of group variables where the domain values are exhaustive, exclusive, and relatively few.

Line charts allow us to visualize measurement variables where the x axis consists of a group or measurement variable whose domain is sequential, e.g. a calendar date.

Use Cases

  • Show trends where x axis represents time, for example monthly revenue over a fiscal year, daily average temperature, a patient’s blood pressure across visits, website traffic per week, or population by decade.

  • Compare trends, for example sales of three product lines side by side, unemployment rates in several countries, control vs. treatment groups in a trial, or actual vs. forecast budget.

  • Plot classical mathematical functions, e.g. linear functions like y=mx+by = mx + b, for example the parabola y=x2y = x^2, the sine wave y=sin⁡xy = \sin x, exponential decay y=e−kty = e^{-kt}, or the hyperbola y=1/xy = 1/x.

  • Show process types, for example the heating curve of water through its phase changes, a capacitor charging and discharging, or a stress–strain curve for a material under load.

A simple example

Let’s look at a simple example.

Below, we visualize a small data set showing sales number over a series of years.

Loading...

To create a line graph in Pandas, you can just call .plot() by itself.

Line graphs are the default plot type.

In the example below, we set x to Year and y to Sales.

<Figure size 640x480 with 1 Axes>

Of course, we can also call the .line() method explicitly.

<Figure size 640x480 with 1 Axes>

Or we can set the kind argument to line

<Figure size 640x480 with 1 Axes>

Another simple example

In this example, we demonstrate how to plot more than one variable in the same figure.

We create data showing number of units sold per month for two products, AA and BB.

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

Using Pandas’ indexes

As we saw earlier, Pandas defaults to showing the index of a data frame on the x axis if x is left unspecified.

Here we set the index to Month, since the values are unique over the observations.

Then, since the remaining non-index features are related, we don’t need to specify those, either. Pandas assumes you want to show them all.

<Figure size 640x480 with 1 Axes>

Here we change the style of plot to show points as well as lines.

<Figure size 640x480 with 1 Axes>
image.png

We can set the attributes of multiple lines by passing lists to the arguments.

<Figure size 640x480 with 1 Axes>

Note that these data can be visualized with a bar chart.

However, they are better visualized with a line graph to show the trend of the data over the sequence.

The bar chart is useful here is you want to emphasize differences between AA and BB per month.

<Figure size 640x480 with 1 Axes>

A better example

Let’s look at the mpg dataset provided by Seaborn.

Let’s use these data to see how cars in different countries have changed over the years

Loading...

To compare measurements over year and origin, let’s create a wide table with hierarchical columns.

Loading...

Note the structure of this table.

The series from the index will define the x-axis and the series associated with the columns will define separate y-axis values.

The result will be three plots for each aggregated feature.

Comparisons

Now, with the table structured this way, we can easily iterate through the measurement variables and generate graphs that compare origin values within each aggregated measure.

<Figure size 600x300 with 1 Axes>
<Figure size 600x300 with 1 Axes>
<Figure size 600x300 with 1 Axes>
<Figure size 600x300 with 1 Axes>

Comparing these plots, we can see a couple of things.

First, as mpg went up during the 1970s, horsepower went down.

Second, the United States has favored horsepower over mpg in comparison to Europe and Japan.

What else can you see?

A more complex example

Let’s look another example the contains multiple measurements that can be plotted against time.

John Arbuthnot’s (1710) data set describes male and female births for London from 1629–1710.

During every one of the 81 years, there were more male christenings (i.e. births) than female christenings.

As Arbuthnot asked, is this difference due to chance or did it mean the birth ratio was actually not 1:11:1?

<class 'pandas.DataFrame'>
RangeIndex: 82 entries, 0 to 81
Data columns (total 8 columns):
 #   Column     Non-Null Count  Dtype  
---  ------     --------------  -----  
 0   rownames   82 non-null     int64  
 1   Year       82 non-null     int64  
 2   Males      82 non-null     int64  
 3   Females    82 non-null     int64  
 4   Plague     82 non-null     int64  
 5   Mortality  82 non-null     int64  
 6   Ratio      82 non-null     float64
 7   Total      82 non-null     float64
dtypes: float64(2), int64(6)
memory usage: 5.3 KB
Loading...

Here are what the column names stand for:

  • Year: The year, ranging from 1629 to 1710.

  • Males: Number of male christenings (births).

  • Females: Number of female christenings (births).

  • Plague: Number of deaths from the Plague.

  • Mortality: Total deaths (all causes combined) for that calendar year.

  • Ratio: Ration of Males to Females.

  • Total: The total number of births scaled in thousands (000s).

Now, let’s look at Total, the total number of births during this period.

<Figure size 640x480 with 1 Axes>

For sake of comparison, look at how these same data appear when plotted as a bar chart. What differences do you notice in how the axes are represented?

<Figure size 640x480 with 1 Axes>

In any case, we can see a big trough between around 1640 and 1665.

Let’s look at all the variables together to see in any variables shed light on this.

To do this, we can use the subplots argument.

<Figure size 750x1500 with 6 Axes>

It appears there are two general kinds of trend here — those that show births, and those that show deaths. It would be nice to compare them.

Let’s compare Total to Mortality.

<Figure size 640x480 with 1 Axes>

This turns out to be not very useful.

The domains of the two variables are so different that one dwarfs the other.

One quick solution to this problem is to normalize both series by getting their Z-scores.

zscore(x)=(x−μ)/σzscore(x) = (x - \mu) / \sigma
<Figure size 640x480 with 1 Axes>

But there is a better way, at least from the perspective of visualization.

Showing two y-axis scales on the same axes

When we compare two related variables come from different domains, it becomes a problem to show them on the same axes.

Matplotlib provides a function to solve this problem -- ax.twinx().

This function take the Axes object returned by a Pandas plot and creates a new Axes object that will be overlaid on the first.

In the result, the left spine represents the first plot while right spine represents the second.

<Figure size 640x480 with 2 Axes>

Clearly, there is more work to make this plot production ready, but we are well on our way.

Plotting mathematical functions

Line charts are also useful for plotting classicial mathematical functions, where yy is a function of xx, i.e. y=f(x)y = f(x).

Loading...
<Figure size 640x480 with 1 Axes>
Loading...
<Figure size 640x480 with 1 Axes>