Line Chart with Several Lines

logo of a chart:ScatterConnected

In a previous post, we saw how to create simple line chart, and in another one how to apply basic customization.

This post explains how to make a line chart with several lines with matplotlib.

Libraries

First, we need to load a few libraries:

  • matplotlib: for creating/styling the plot
  • pandas: for data manipulation
  • numpy for data generation
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

Dataset

Let's create 4 simple columns created with numpy that we put in a pandas dataframe.

df = pd.DataFrame({
    'x_values': range(1,11),
    'y1_values': np.random.randn(10),
    'y2_values': np.random.randn(10)+range(1,11),
    'y3_values': np.random.randn(10)+range(11,21)
    }
)

Mutliple line charts

Here we display 3 different line charts with different style properties:

plt.plot(
    'x_values', 'y1_values', data=df,
    marker='o', # marker type
    markerfacecolor='blue', # color of marker
    markersize=12, # size of marker
    color='skyblue', # color of line
    linewidth=4 # change width of line
)

plt.plot(
    'x_values', 'y2_values', data=df,
    marker='', # no marker
    color='olive', # color of line
    linewidth=2 # change width of line
)

plt.plot(
    'x_values', 'y3_values', data=df,
    marker='', # no marker
    color='darkred', # color of line
    linewidth=3, # change width of line
    linestyle='dashed', # change type of line
    label="toto" # label for legend
)

# show legend
plt.legend()

# show graph
plt.show()

Going further

This post explains how to customize a the line of a line chart with matplotlib.

You might be interested in a more advanced line chart customization and how to have a log scale.

🚨 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