Add Legends in Matplotlib Subplots Using Python

When I started using Python for data visualization, one of the first libraries I mastered was Matplotlib.

It’s powerful, flexible, and widely used across industries like finance, healthcare, and education. But one thing that often confuses beginners is how to add legends in subplots.

I faced this challenge myself when I was working on multiple charts for sales data in different US states. I wanted each subplot to have its own legend, but sometimes I also needed a single shared legend.

Why Legends Matter in Matplotlib Subplots

When you create multiple subplots, each subplot may represent a different dataset. Without legends, it’s difficult to know which line, scatter, or bar belongs to which category.

Adding legends makes your Python visualization clear, professional, and easy to understand.

Method 1 – Add Legends to Each Subplot Individually

The simplest way is to add a legend to each subplot separately. This is useful when each subplot represents different categories or datasets, such as sales in California vs. New York.

import matplotlib.pyplot as plt
import numpy as np

# Sample data (USA sales data simulation)
months = np.arange(1, 7)
california_sales = [200, 250, 300, 280, 350, 400]
newyork_sales = [180, 220, 260, 240, 300, 330]

# Create subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))

# California subplot
ax1.plot(months, california_sales, label="California Sales", color="blue")
ax1.set_title("California Sales Data")
ax1.set_xlabel("Month")
ax1.set_ylabel("Sales")
ax1.legend()

# New York subplot
ax2.plot(months, newyork_sales, label="New York Sales", color="green")
ax2.set_title("New York Sales Data")
ax2.set_xlabel("Month")
ax2.set_ylabel("Sales")
ax2.legend()

plt.tight_layout()
plt.show()

You can see the output in the screenshot below.

Add Legends in Matplotlib Subplots Using Python

This code creates two subplots side by side. Each subplot has its own legend. It’s a good approach when you want legends to be local to each subplot.

Method 2 – Add a Single Shared Legend for All Subplots

Sometimes, you may want one shared legend for the entire figure instead of repeating legends in each subplot.

This is useful when the same categories appear across all subplots.

import matplotlib.pyplot as plt
import numpy as np

# Sample data for two states
months = np.arange(1, 7)
california_sales = [200, 250, 300, 280, 350, 400]
newyork_sales = [180, 220, 260, 240, 300, 330]

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))

# Plot data on both subplots
line1, = ax1.plot(months, california_sales, label="California", color="blue")
line2, = ax2.plot(months, newyork_sales, label="New York", color="green")

# Titles and labels
ax1.set_title("California Sales")
ax2.set_title("New York Sales")
ax1.set_xlabel("Month")
ax2.set_xlabel("Month")
ax1.set_ylabel("Sales")
ax2.set_ylabel("Sales")

# Add one shared legend
fig.legend([line1, line2], ["California", "New York"], loc="upper center", ncol=2)

plt.tight_layout()
plt.show()

You can see the output in the screenshot below.

Add Legends to Matplotlib Subplots in Python

In this Python example, the single legend appears at the top, covering both subplots. This makes the visualization cleaner and avoids repetition.

Method 3 – Place the Legend Outside the Subplots

Another common requirement is to move the legend outside the subplot area. This is great when you have multiple categories and don’t want the legend to overlap with the chart.

import matplotlib.pyplot as plt
import numpy as np

# Simulated USA sales data for three states
months = np.arange(1, 7)
california_sales = [200, 250, 300, 280, 350, 400]
newyork_sales = [180, 220, 260, 240, 300, 330]
texas_sales = [150, 200, 220, 210, 260, 280]

fig, ax = plt.subplots(figsize=(8, 5))

# Plot multiple states
ax.plot(months, california_sales, label="California", color="blue")
ax.plot(months, newyork_sales, label="New York", color="green")
ax.plot(months, texas_sales, label="Texas", color="red")

ax.set_title("Sales Data Across States")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")

# Place legend outside
ax.legend(loc="center left", bbox_to_anchor=(1, 0.5))

plt.tight_layout()
plt.show()

You can see the output in the screenshot below.

Python Matplotlib Add Legends Subplots

Here, the legend is placed outside the right side of the subplot. This technique is often used in professional reports and dashboards.

Method 4 – Use Subplots with Loop and Legends

When working with many subplots, manually adding legends can be repetitive. Instead, you can use a loop to create subplots and add legends dynamically.

import matplotlib.pyplot as plt
import numpy as np

# Example: Sales data for 3 US states
states = {
    "California": [200, 250, 300, 280, 350, 400],
    "New York": [180, 220, 260, 240, 300, 330],
    "Texas": [150, 200, 220, 210, 260, 280]
}

months = np.arange(1, 7)

fig, axes = plt.subplots(1, 3, figsize=(15, 5))

# Loop through states and subplots
for ax, (state, sales) in zip(axes, states.items()):
    ax.plot(months, sales, label=f"{state} Sales")
    ax.set_title(f"{state} Data")
    ax.set_xlabel("Month")
    ax.set_ylabel("Sales")
    ax.legend()

plt.tight_layout()
plt.show()

You can see the output in the screenshot below.

Add Legends in Python Matplotlib Subplots

This Python method is efficient when you have multiple subplots with similar structures. It helps reduce code duplication and keeps your script clean.

Method 5 – Customize Legends in Subplots

Finally, you can customize legends by changing their location, font size, and style. This makes your Python visualization more polished.

import matplotlib.pyplot as plt
import numpy as np

months = np.arange(1, 7)
california_sales = [200, 250, 300, 280, 350, 400]
newyork_sales = [180, 220, 260, 240, 300, 330]

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))

ax1.plot(months, california_sales, label="California", color="blue")
ax2.plot(months, newyork_sales, label="New York", color="green")

ax1.set_title("California Sales")
ax2.set_title("New York Sales")

# Custom legends
ax1.legend(loc="upper left", fontsize=10, frameon=True)
ax2.legend(loc="lower right", fontsize=12, frameon=False)

plt.tight_layout()
plt.show()

Here, I adjusted the legend position and style to make the chart look more professional. This is especially useful when preparing reports for clients or management.

Adding legends in Matplotlib subplots using Python is not difficult once you know the right methods. I showed you how to:

  • Add legends to each subplot individually
  • Create a single shared legend
  • Place legends outside subplots
  • Use loops for multiple subplots
  • Customize legends for better presentation

These techniques are exactly what I use in my own Python projects when working with real-world data in the USA. With these methods, your visualizations will look clearer and more professional.

You can also read other Matplotlib articles:

Leave a Comment

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.