How to Plot Line Charts in Python

Line charts are typically used to show the overall trend of a certain topic. For instance, you can use a line chart to show the overall price movement of a stock or people’s interest in a certain topic or object.

The following shows the core syntax to plot line charts in Python, including Seaborn, matplotlib, and Pandas.

  • Seaborn: sns.lineplot(data=df, x=’column_x’, y=’column_y’)
  • matplotlib: plt.plot(df[‘column_x’], df[‘column_y’])
  • Pandas: df.plot.line(x=’column_x’, y=’column_y’)

Example 1: Seaborn to plot line charts in Python

import seaborn as sns
import pandas as pd

# reed data from GitHub
df=pd.read_csv("https://raw.githubusercontent.com/TidyPython/data_visualization/main/may_flights.csv")

# print out the data
print(df)

# use seaborn to plot a line chart
sns.lineplot(data=may_flights, x="year", y="passengers")

The following is the data output:

    Unnamed: 0  year month  passengers
0            4  1949   May         121
1           16  1950   May         125
2           28  1951   May         172
3           40  1952   May         183
4           52  1953   May         229
5           64  1954   May         234
6           76  1955   May         270
7           88  1956   May         318
8          100  1957   May         355
9          112  1958   May         363
10         124  1959   May         420
11         136  1960   May         472

The following is the line chart plot using Seaborn in Python.

Plot Line Charts in Python using Seaborn
Plot Line Charts in Python using Seaborn

Example 2: Use matplotlib to plot line charts in Python

import matplotlib.pyplot as plt
import pandas as pd

# reed data from GitHub
df=pd.read_csv("https://raw.githubusercontent.com/TidyPython/data_visualization/main/may_flights.csv")

# use seaborn to plot a line chart
plt.plot(df["year"], df["passengers"])

The following is the line chart plot.

Plot Line Charts in Python using matplotlib
Plot Line Charts in Python using matplotlib

Example 3: use Pandas to plot line charts in Python

import pandas as pd
import matplotlib.pyplot as plt

# reed data from GitHub
df=pd.read_csv("https://raw.githubusercontent.com/TidyPython/data_visualization/main/may_flights.csv")

# use Pandas to plot line charts
df.plot.line(x="year", y="passengers")

# plt.show() is optional in some IDE such as Jupyter
plt.show()

The following is the line chart plot.

Plot Line Charts in Python using Pandas
Plot Line Charts in Python using Pandas

Example 4: Generate data from scratch to plot line charts in Python

All the first 3 examples read data from GitHub. In contrast, the following will use NumPy package to generate X and Y.

Y=X2

In particular, it generates a range of data (0 ~ 20), and then square the X as Y. Then, we can plot a line chart to illustrate how to plot a line chart in Python.

import numpy as np
import matplotlib.pyplot as plt

# generate data from scratch
x_simple=np.linspace(0, 20, 100)
y_simple=x_simple*x_simple

# plot line charts using matplotlib
plt.plot(x_simple, y_simple)
plt.xlabel("X")
plt.ylabel("Y")
Generate data from scratch to plot line charts in Python
Generate data from scratch to plot line charts in Python

Example 5: Plot Google Trends Scores of Peloton

Google Trends is a site by Google that analyzes the popularity of search queries in Google Search. Thus, if a word is more popular, Google Trends scores will be higher.

Peloton’s Google Trends data is used to plot the overall trends of consumers’ interest in Peloton overtime, from March 2019 to March 2022.

X = Different Weeks

Y= Google Trends scores of Peloton

Step 1: Read data and plot the line chart

The code below reads the CSV data file from GitHub into the environment and prints it out.

import pandas as pd
import matplotlib.pyplot as plt

# read data from GitHub and print it out
url="https://raw.githubusercontent.com/TidyPython/data_visualization/main/Peloton_Google_Trends.csv"
data_Peloton=pd.read_csv(url)
print(data_Peloton)

# use matplotlib to plot the line chart
plt.plot('Week', 'Peloton',data=data_Peloton)

# plt.show() is optional in some IDE such as Jupyter
plt.show()

Output:

          Week  Peloton
0    3/10/2019       10
1    3/17/2019       11
2    3/24/2019       10
3    3/31/2019        9
4     4/7/2019        8
..         ...      ...
156   3/6/2022       19
157  3/13/2022       17
158  3/20/2022       16
159  3/27/2022       15
160   4/3/2022       15

[161 rows x 2 columns]
[Finished in 1.3s]
Line Chart of Peloton Google Trends in Python
Line Chart of Peloton Google Trends in Python

Step 2: Change the interval on the x-axis

As you can see, while the y-axis looks great, the x-axis looks very crowded. To solve that problem, we need to use reduce the number of labels shown on the x-axis.

The following is the solution. The basic idea is to specify the interval. There are quite a few different methods of doing that, see the figure below.

Plot interval in Python
Plot interval in Python

The following is the complete Python code to plot the line chart and the output.

# updated version of Python code to plot line charts
import pandas as pd
import matplotlib.pyplot as plt

url="https://raw.githubusercontent.com/TidyPython/data_visualization/main/Peloton_Google_Trends.csv"
data_Peloton=pd.read_csv(url)

# use matplotlib to plot the line chart
plt.plot('Week', 'Peloton',data=data_Peloton)

# added line of statement to change the interval
plt.gca().xaxis.set_major_locator(plt.MultipleLocator(30))

# change the font size of the title
plt.title("Google Trends of Peloton",fontdict = {'fontsize' : 15})

# plt.show() is optional in some IDE such as Jupyter
plt.show()

Output:

Line Chart of Peloton Google Trends in Python
Line Chart of Peloton Google Trends in Python

Other Resource