Line Graphs
DS 2023 | Communicating with Data

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 , for example the parabola , the sine wave , exponential decay , or the hyperbola .
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.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as snsdata = {
'year': [2021, 2022, 2023, 2024, 2025, 2026],
'sales': [100, 120, 170, 160, 210, 240]
}
df1 = pd.DataFrame(data)
df1To 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.
df1.plot(x='year', y='sales')
plt.show()
Of course, we can also call the .line() method explicitly.
df1.plot.line(x='year', y='sales')
plt.show()
Or we can set the kind argument to line
df1.plot(x='year', y='sales', kind='line')
plt.show()
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, and .
data = {
'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
'Product_A': [15, 20, 35, 30, 45],
'Product_B': [25, 18, 22, 40, 48]
}
df2 = pd.DataFrame(data)
df2.plot.line(x='Month', y=['Product_A', 'Product_B'], title="Business is Booming")
plt.show()
df2.plot.line(x='Month', y=['Product_A', 'Product_B'], subplots=True)
plt.show()
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.
df3 = df2.set_index('Month')
df3.plot()
plt.show()
Here we change the style of plot to show points as well as lines.
df3.Product_A.plot.line(style = '-o')
plt.show()

We can set the attributes of multiple lines by passing lists to the arguments.
df3.plot.line(style=['o-', 's--'], color=['blue', 'green'])
plt.show()
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 and per month.
df3.plot.bar(rot=0)
plt.show()
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
mpg = sns.load_dataset('mpg')
mpg.head()To compare measurements over year and origin, let’s create a wide table with hierarchical columns.
mpg_measures = ['horsepower','mpg','acceleration','weight']mpg_wide = mpg.pivot_table(index='model_year', columns='origin', values=mpg_measures, aggfunc='mean')
mpg_wideNote 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.
for measure_col in mpg_measures:
mpg_wide[measure_col].plot(figsize=(6,3), title=measure_col)
plt.show()



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 ?
# data_url = "https://vincentarelbundock.github.io/Rdatasets/csv/HistData/Arbuthnot.csv"
data_url = "https://virginia.box.com/shared/static/tpree5hiavq5et794htm7208vc0anulm.csv"
dfx = pd.read_csv(data_url)
dfx.info()
dfx = dfx.set_index('Year')
dfx = dfx.drop("rownames", axis=1)
dfx.head()<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
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.
dfx['Total'].plot(style='.-', legend=False, title="Total Births per Year")
plt.show()
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?
dfx['Total'].plot.bar()
plt.show()
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.
dfx.plot(subplots=True, figsize=(7.5,15))
plt.show()
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.
dfx[['Total','Mortality']].plot()
plt.show()
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.
dfx1 = dfx[['Total','Mortality']]
dfx1.columns = ['Births','Deaths']
(
(dfx1 - dfx1.mean()) / dfx1.std()
).plot()
plt.grid()
plt.show()
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.
ax = dfx1['Births'].plot(style='.-', legend=True)
ax2 = ax.twinx()
dfx1['Deaths'].plot(ax=ax2, color='orange', style='.-', legend=True)
ax.set_ylabel('Births'), ax2.set_ylabel('Deaths')
plt.title("Comparing Birth to Mortality")
plt.show()
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 is a function of , i.e. .
df = pd.DataFrame()
df['x'] = np.arange(0, 5 * np.pi, 0.1)
df['sin_x'] = np.sin(df.x)
df.head()df.plot(x='x', y='sin_x')
plt.grid()
plt.show()
df['cos_x'] = np.cos(df.x)
df.head()df.plot(x='x', y=['sin_x','cos_x'])
plt.grid()
plt.show()