Multiple Lines on Line Plot or Time Series with Matplotlib

As a Python developer, I’ve worked extensively with data visualization. One of the most common tasks I encounter is plotting multiple lines on a single line plot or time series chart. This is especially useful when comparing trends across different datasets, like tracking sales performance across multiple states or monitoring temperature changes in various cities.

While Matplotlib is a powerful library for plotting in Python, beginners often find it tricky to plot multiple lines clearly and effectively. In this article, I’ll walk you through different methods to plot multiple lines on a line plot or time series using Matplotlib. I’ll share practical examples that you can adapt to your projects.

Let’s get right in!

Methods to Plot Multiple Lines on a Line Plot

Plotting multiple lines helps compare different variables or groups over the same time frame or categories. For example, if you want to analyze the average monthly temperatures of New York, Los Angeles, and Chicago, plotting all three on the same graph makes it easier to visualize differences and trends.

Matplotlib makes this simple, but there are a few ways to do it depending on your data structure and preferences.

Read Matplotlib fill_between

Method 1: Plot Multiple Lines Using Multiple plt.plot() Calls

This is the easy method. You simply call plt.plot() for each line you want to add to the plot.

Here’s an example where I plot monthly sales data for three US states:

import matplotlib.pyplot as plt

# Sample data: Monthly sales (in thousands) for three states
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
california_sales = [50, 55, 60, 58, 65, 70]
texas_sales = [45, 48, 50, 52, 54, 58]
florida_sales = [40, 42, 45, 47, 50, 53]

plt.figure(figsize=(10, 6))

plt.plot(months, california_sales, marker='o', label='California')
plt.plot(months, texas_sales, marker='s', label='Texas')
plt.plot(months, florida_sales, marker='^', label='Florida')

plt.title('Monthly Sales Comparison (in thousands)')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.legend()
plt.grid(True)
plt.show()

You can refer to the screenshot below to see the output.

Multiple Lines on Line Plot or Time Series Matplotlib

Explanation:

  • Each call to plt.plot() adds a new line.
  • Using different markers (o, s, ^) helps distinguish the lines.
  • The label parameter is used to create a legend.

This method is intuitive and works well when you have a manageable number of lines.

Check out Plot Multiple Graphs Generated Inside a For Loop in Matplotlib

Method 2: Plot Multiple Lines Using a Loop

When you have many lines to plot, calling plt.plot() repeatedly can be tedious. Instead, storing your datasets in a dictionary or list and looping through them is more efficient.

Here’s how I do it with temperature data from multiple cities:

import matplotlib.pyplot as plt

# Monthly average temperatures (°F) for US cities
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
city_temps = {
    'New York': [32, 35, 45, 55, 65, 75],
    'Los Angeles': [58, 60, 62, 65, 68, 72],
    'Chicago': [28, 30, 40, 50, 60, 70],
    'Houston': [50, 55, 65, 70, 75, 80]
}

plt.figure(figsize=(10, 6))

for city, temps in city_temps.items():
    plt.plot(months, temps, marker='o', label=city)

plt.title('Average Monthly Temperatures of US Cities')
plt.xlabel('Month')
plt.ylabel('Temperature (°F)')
plt.legend()
plt.grid(True)
plt.show()

You can refer to the screenshot below to see the output.

Matplotlib Multiple Lines on Line Plot or Time Series with

Why I Like This Approach:

  • It scales well when you have many lines.
  • It’s easy to add or remove cities.
  • The code stays clean and readable.

Method 3: Plot Multiple Lines Using Pandas DataFrame with Matplotlib

If you work with time series data, chances are you’re using Pandas. Pandas integrates smoothly with Matplotlib, allowing you to plot multiple columns directly.

Let me show you an example using quarterly GDP growth rates for three US regions:

import pandas as pd
import matplotlib.pyplot as plt

# Sample quarterly GDP growth rates (%)
data = {
    'Q1': [2.1, 1.8, 2.5],
    'Q2': [2.3, 2.0, 2.7],
    'Q3': [2.5, 2.2, 3.0],
    'Q4': [2.7, 2.5, 3.2]
}

regions = ['Northeast', 'Midwest', 'South']
df = pd.DataFrame(data, index=regions).T  # Transpose for time series on rows

df.plot(marker='o', figsize=(10, 6))

plt.title('Quarterly GDP Growth Rates by Region')
plt.xlabel('Quarter')
plt.ylabel('GDP Growth Rate (%)')
plt.grid(True)
plt.show()

You can refer to the screenshot below to see the output.

Multiple Lines on Line Plot or Time Series with Matplotlib

What Makes This Method Great:

  • You don’t have to call plt.plot() multiple times.
  • Pandas automatically handles the legend and axis labels.
  • It’s perfect for time series data with labeled columns.

Read Module ‘matplotlib’ has no attribute ‘artist’

Method 4: Plot Multiple Time Series with DateTime Index

Often, time series data uses actual dates or timestamps. Matplotlib handles this well when you use a DateTime index in Pandas.

Here’s an example plotting daily COVID-19 case counts for three US states over a week:

import pandas as pd
import matplotlib.pyplot as plt

# Sample daily COVID-19 cases
dates = pd.date_range(start='2024-04-01', periods=7)
data = {
    'California': [500, 520, 540, 580, 600, 620, 630],
    'Texas': [450, 460, 470, 480, 490, 500, 510],
    'Florida': [400, 410, 420, 430, 440, 450, 460]
}

df = pd.DataFrame(data, index=dates)

df.plot(marker='o', figsize=(10, 6))

plt.title('Daily COVID-19 Cases in Selected US States')
plt.xlabel('Date')
plt.ylabel('Number of Cases')
plt.grid(True)
plt.show()

Key Takeaways:

  • Using a DateTime index makes the x-axis show dates automatically.
  • Matplotlib formats the date ticks nicely.
  • This method is ideal for real-world time series data.

Tips for Better Multiple Line Plots

  • Use Distinct Colors and Markers: It helps differentiate lines.
  • Add a Legend: Always use plt.legend() or let Pandas handle it.
  • Grid Lines: Makes the plot easier to read.
  • Labels and Titles: Always add axis labels and a title for clarity.
  • Adjust Figure Size: Use figsize to make your plot readable.
  • Handle Overlapping Lines: If many lines overlap, consider interactive plots or subplots.

Plotting multiple lines on a single plot is a fundamental skill for any data analyst or Python developer working with time series or comparative data. Whether you’re analyzing sales across states, temperatures in cities, or any other trend, Matplotlib offers flexible ways to visualize your data.

I hope these methods help you create clear and insightful line plots for your projects. If you have any questions or want to share your tips, feel free to reach out!

Happy plotting!

Other articles you may like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.