How to plot multiple lines with Python, Seaborn and Matplotlib?

Today we’ll learn to draw a bit more sophisticated lineplots that display multiple lines. We’ll provide examples leveraging the two popular Python Data Visualization libraries: Matplotlib and Seaborn.

Importing libraries

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np'ggplot')

Create dummy data

We’ll use numpy to quickly generate simple x,y coordinate data.

x = np.linspace (1,10,25)
y = x * 2
z = np.exp(x)

Matplotlib multiple line graph

We’ll use the Matplotlib to generate a simple multi line graph.

# plotting multiple lines from array

Adding a legend to the chart

We can easily add a legend to the chart using the plt.legend() method as shown below. In this example we also customize the marker type and line color. We also use the label parameter to define the appropiate label legend.

# multiple lines with legend
plt.plot(x,y,marker='.', color='r', label= 'accelerated growth')
plt.plot(x,z, marker = '+', color = 'g',label = 'exponential growth')

Multiple line plots in one figure

When dealing with more complex multi variable data, we use subplot grids to render multiple graphs. Here’s a a simple example.

# multiple graphs one figure

fig, ax = plt.subplots(2,1, sharex=True)

Seaborn multiple lines chart

We’ll now show an example of using Seaborn and specifically the lineplot chart. We’ll first go ahead and create a DataFrame that we later feed into a couple of lineplot calls, each drawing one plot.

We can obviously construct the DataFrrame by reading excel, text, json or csv files as well as connecting to databases or data APIs.

# seaborn plot multiple lines

import pandas as pd
import seaborn as sns

my_dict = dict(x=x,y=y,z=z)
data = pd.DataFrame (my_dict)
fig, ax = plt.subplots()
ax= sns.lineplot(x='x', y='y', data=data)
ax1 = sns.lineplot(x='x', y='z', data=data)