Line chart with matplotlib

logo of a chart:Line

A line chart or line graph is a type of chart which displays information as a series of data points called ‘markers’ connected by straight line segments.

It is similar to a scatter plot except that the measurement points are ordered (typically by their x-axis value) and joined with straight line segments. This post will show how to plot a basic line chart using matplotlib.

Libraries

First, we need to load a few libraries:

  • matplotlib: for creating/styling the plot
  • seaborn: for creating the plot
  • numpy for data generation
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

Basic Lineplot

You can create a basic line chart with the plot() function of matplotlib library. If you give only a serie of values, matplotlib will consider that these values are ordered and will use values from 1 to n to create the X axis (figure 1):

# create data
values=np.cumsum(np.random.randn(1000,1))
 
# use the plot function
plt.plot(values)

# show the graph
plt.show()

Seaborn Customization

For a more trendy look, you can use the set_theme() function of seaborn library. You will automatically get the look of figure 2.

sns.set_theme()

# create data
values=np.cumsum(np.random.randn(1000,1))
 
# use the plot function
plt.plot(values)

# show the graph
plt.show()

Use lineplot with unordered data

You can also make a line chart from 2 series of values (X and Y axis). However, make sure that your X axis values are ordered! If not, you will get this kind of figure (figure 3).

# import the iris dataset
df = sns.load_dataset('iris')
 
# plot
plt.plot( 'sepal_width', 'sepal_length', data=df)

# show the graph
plt.show()

Use lineplot with ordered data

If your X data is ordered, then you will get a similar figure as figure 1:

import pandas as pd
df=pd.DataFrame({'xvalues': range(1,101), 'yvalues': np.random.randn(100) })
 
# plot
plt.plot( 'xvalues', 'yvalues', data=df)

# show the graph
plt.show()

Going further

This post explains how to customize a line plot with matplotlib and seaborn libraries.

You might be interested in how to use 2 different y axis for 2 lines and how to have a log scale.

Timeseries

🚨 Grab the Data To Viz poster!


Do you know all the chart types? Do you know which one you should pick? I made a decision tree that answers those questions. You can download it for free!

    dataviz decision tree poster