Plot Multiple Lines with Legends in Matplotlib

One of the most common tasks in data visualization is plotting multiple lines on the same graph. Whether you’re tracking sales trends across different US states or comparing temperature changes over months, displaying multiple lines with clear legends makes your charts easier to understand.

In this article, I’ll walk you through practical, easy-to-follow methods to plot multiple lines with legends using Matplotlib. I’ll share tips from my own experience to help you create clean and professional charts that speak volumes.

Let’s get into the topic!

Methods to Plot Multiple Lines with Legends in Matplotlib

When you have more than one dataset to visualize, plotting each line separately but on the same chart helps you compare trends side by side. Legends serve as a key to identify which line corresponds to which dataset, making your visualization intuitive.

Imagine you’re analyzing quarterly sales data for three major US cities , New York, Los Angeles, and Chicago. Plotting all three on one graph with distinct colors and legends helps stakeholders quickly grasp the differences and similarities.

Read Matplotlib Unknown Projection ‘3d’

Method 1: Plot Multiple Lines Using Basic Plot with Labels

The simplest way to plot multiple lines with legends is by calling plt.plot() multiple times and specifying the label for each line. After plotting, you call plt.legend() to display the legend.

Here’s how I typically do it:

import matplotlib.pyplot as plt

# Quarterly sales data for three US cities
quarters = ['Q1', 'Q2', 'Q3', 'Q4']
ny_sales = [25000, 27000, 30000, 32000]
la_sales = [22000, 24000, 26000, 28000]
chi_sales = [20000, 21000, 23000, 25000]

plt.plot(quarters, ny_sales, label='New York', marker='o')
plt.plot(quarters, la_sales, label='Los Angeles', marker='s')
plt.plot(quarters, chi_sales, label='Chicago', marker='^')

plt.title('Quarterly Sales Comparison')
plt.xlabel('Quarter')
plt.ylabel('Sales in USD')
plt.legend()  # Display the legend
plt.grid(True)
plt.show()

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

Plot with Legends in Matplotlib
  • Each line has a clear label that appears in the legend.
  • Markers differentiate the points visually.
  • The legend helps identify each city’s sales trend.

Check out What is the add_axes Matplotlib

Method 2: Plot Multiple Lines Using a Loop for Scalability

When you have many datasets, writing multiple plt.plot() calls can get tedious. I prefer using a loop, especially when working with data from pandas or dictionaries.

Here’s an example with sales data stored in a dictionary:

import matplotlib.pyplot as plt

quarters = ['Q1', 'Q2', 'Q3', 'Q4']
sales_data = {
    'New York': [25000, 27000, 30000, 32000],
    'Los Angeles': [22000, 24000, 26000, 28000],
    'Chicago': [20000, 21000, 23000, 25000],
    'Houston': [18000, 19000, 21000, 23000]
}

for city, sales in sales_data.items():
    plt.plot(quarters, sales, label=city, marker='o')

plt.title('Quarterly Sales Comparison Across Cities')
plt.xlabel('Quarter')
plt.ylabel('Sales in USD')
plt.legend()
plt.grid(True)
plt.show()

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

Multiple Lines with Legends in Matplotlib
  • Easily scalable to any number of lines.
  • Keeps your code clean and manageable.
  • Automatically generates legends from dictionary keys.

Read Matplotlib Set Axis Range

Method 3: Customize Legends for Better Clarity

Sometimes, the default legend placement or style doesn’t fit your needs. Matplotlib allows you to customize legends extensively.

Here’s how I customize legends for better presentation:

plt.plot(quarters, ny_sales, label='New York', marker='o', linestyle='-')
plt.plot(quarters, la_sales, label='Los Angeles', marker='s', linestyle='--')
plt.plot(quarters, chi_sales, label='Chicago', marker='^', linestyle=':')

plt.title('Quarterly Sales Comparison')
plt.xlabel('Quarter')
plt.ylabel('Sales in USD')

# Place legend outside the plot area on the right
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), title='Cities', fontsize='small', shadow=True)

plt.grid(True)
plt.tight_layout()  # Adjust layout to make room for legend
plt.show()

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

Legends in Matplotlib to Plot Multiple Lines

Key points:

  • loc and bbox_to_anchor control legend position.
  • Adding a title to the legend improves readability.
  • Using different line styles and markers enhances distinction.

Check out Matplotlib Secondary y-Axis

Method 4: Plot Multiple Lines from a Pandas DataFrame

When working with data analysis in the USA, pandas is a powerful tool. I often plot multiple lines directly from a DataFrame, which simplifies the process.

Example:

import pandas as pd
import matplotlib.pyplot as plt

data = {
    'Quarter': ['Q1', 'Q2', 'Q3', 'Q4'],
    'New York': [25000, 27000, 30000, 32000],
    'Los Angeles': [22000, 24000, 26000, 28000],
    'Chicago': [20000, 21000, 23000, 25000]
}

df = pd.DataFrame(data)
df.set_index('Quarter', inplace=True)

df.plot(marker='o')
plt.title('Quarterly Sales from DataFrame')
plt.xlabel('Quarter')
plt.ylabel('Sales in USD')
plt.legend(title='Cities')
plt.grid(True)
plt.show()
  • Direct plotting from DataFrame columns.
  • Automatic legend generation from column names.
  • Simplifies code when handling large datasets.

Read Matplotlib Legend Font Size

Tips for Effective Multi-Line Plots with Legends

  • Use distinct colors and markers: Helps differentiate lines.
  • Keep legends readable: Avoid overcrowding by limiting the number of lines or placing legends outside the plot.
  • Label axes and title your plot: Context is key for understanding data.
  • Use grid lines: Enhances the readability of data points.
  • Adjust figure size if needed: For presentations or reports, a larger figure can improve clarity.

Plotting multiple lines with legends in Matplotlib is simple once you get the hang of it. Whether you’re coding quick comparisons or building detailed dashboards, these methods help you present your data clearly and professionally.

If you want to dive deeper, Matplotlib offers many customization options that can make your charts even more insightful. But starting with these basics will get you a long way in visualizing your USA-based datasets effectively.

Feel free to experiment with these examples and adapt them to your projects. Clear visualization often makes the difference between data that’s just numbers and data that tells a story.

You may also like to read other Matplotlib articles:

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.