Python Matplotlib Add a Colorbar to Each Subplot

As a developer, I was working on a Python project where I had to visualize multiple datasets side by side using subplots. Each subplot had its own scale and color mapping. The challenge I faced was how to add a separate colorbar to each subplot in Matplotlib.

At first, I tried to use a single colorbar for all subplots, but it didn’t make sense because each dataset had a different range. That’s when I realized I needed a way to add an individual colorbar to each subplot.

In this tutorial, I’ll show you exactly how I solved this problem. I’ll walk you through different methods of adding a colorbar to each subplot in Python Matplotlib. I’ll also share the complete code examples so you can try them on your own system.

Why Use a Colorbar in Python Matplotlib?

A colorbar is a visual guide that shows the mapping between data values and colors in a plot. When you’re working with heatmaps, scatter plots, or contour plots in Python, the colorbar helps readers interpret the meaning of the colors.

When you have multiple subplots, each subplot may represent a different dataset. Adding a colorbar to each subplot ensures clarity because the reader can immediately see the scale for that specific plot.

Method 1 – Add a Colorbar to Each Subplot Using imshow()

When I first started experimenting, I used the imshow() function in Python Matplotlib. This method is easy and works well when you’re dealing with image-like data such as heatmaps.

Here’s the full Python code:

import matplotlib.pyplot as plt
import numpy as np

# Generate random data for demonstration
data1 = np.random.rand(10, 10) * 100
data2 = np.random.rand(10, 10) * 50

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

# Plot data in first subplot
cax1 = ax1.imshow(data1, cmap='viridis')
ax1.set_title("Dataset 1 (USA Sales Data)")
fig.colorbar(cax1, ax=ax1)

# Plot data in second subplot
cax2 = ax2.imshow(data2, cmap='plasma')
ax2.set_title("Dataset 2 (USA Marketing Data)")
fig.colorbar(cax2, ax=ax2)

# Adjust layout
plt.tight_layout()
plt.show()

I have executed the above example code and added the screenshot below.

Python Matplotlib Add Colorbar to Each Subplot

This code creates two subplots side by side. Each subplot has its own dataset, colormap, and colorbar.

I often use this method when I want to highlight differences between two datasets, for example, comparing sales and marketing performance across the USA states.

Method 2 – Add Colorbars to Subplots in a Loop

Sometimes, you may have more than two subplots. In such cases, repeating the same code for each subplot can be inefficient. I prefer to use a loop in Python to handle this.

Here’s the Python code:

import matplotlib.pyplot as plt
import numpy as np

# Generate multiple datasets
datasets = [np.random.rand(10, 10) * (i+1) * 20 for i in range(4)]

# Create 2x2 subplots
fig, axes = plt.subplots(2, 2, figsize=(8, 8))

# Flatten axes for easy iteration
axes = axes.flatten()

# Loop through datasets and axes
for i, (ax, data) in enumerate(zip(axes, datasets)):
    cax = ax.imshow(data, cmap='coolwarm')
    ax.set_title(f"Subplot {i+1}")
    fig.colorbar(cax, ax=ax)

plt.tight_layout()
plt.show()

I have executed the above example code and added the screenshot below.

Python Matplotlib Add a Colorbar to Each Subplot

With this approach, each subplot automatically gets its own colorbar. This is especially useful when I work with multiple regions in the USA, such as analyzing temperature variations across four different cities.

Method 3 – Use scatter() with Separate Colorbars

Colorbars are not limited to heatmaps. They also work with scatter plots. I often use scatter plots when I want to visualize relationships between variables, such as income vs. spending in different US states.

Here’s how you can add a colorbar to each subplot with scatter plots:

import matplotlib.pyplot as plt
import numpy as np

# Generate random scatter data
x = np.random.rand(50)
y1 = np.random.rand(50)
y2 = np.random.rand(50)
colors1 = np.random.rand(50) * 100
colors2 = np.random.rand(50) * 200

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

# First scatter plot
sc1 = ax1.scatter(x, y1, c=colors1, cmap='viridis')
ax1.set_title("Income vs Spending (East Coast)")
fig.colorbar(sc1, ax=ax1)

# Second scatter plot
sc2 = ax2.scatter(x, y2, c=colors2, cmap='plasma')
ax2.set_title("Income vs Spending (West Coast)")
fig.colorbar(sc2, ax=ax2)

plt.tight_layout()
plt.show()

I have executed the above example code and added the screenshot below.

Add Colorbar to Each Subplot in Python Matplotlib

Each subplot here represents a different region of the USA, and the colorbars show the scale of the values. This makes the plots much easier to interpret.

Method 4 – Customize Colorbars in Subplots

Sometimes, you may want to customize the colorbar to make it more professional. For example, I often add labels or adjust the orientation of the colorbar.

Here’s how I do it in Python:

import matplotlib.pyplot as plt
import numpy as np

# Data for customization
data = np.random.rand(10, 10) * 75

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

# Plot data
cax = ax.imshow(data, cmap='inferno')
ax.set_title("Customized Colorbar Example")

# Add customized colorbar
cbar = fig.colorbar(cax, ax=ax, orientation='horizontal')
cbar.set_label("Temperature (°F)")

plt.tight_layout()
plt.show()

I have executed the above example code and added the screenshot below.

Add a Colorbar to Each Subplot Matplotlib

This approach is helpful when I want to present data to clients in the USA. A labeled and well-formatted colorbar makes the visualization look professional and easy to understand.

Things to Keep in Mind

Use consistent colormaps: If your datasets are related, using the same colormap across subplots improves readability.

  • Adjust subplot spacing: Without tight_layout(), colorbars may overlap with other elements.
  • Consider audience: For USA-based stakeholders, I often use Fahrenheit instead of Celsius or dollars instead of euros. This makes the charts more relatable.

Adding a colorbar to each subplot in Python Matplotlib may look tricky at first, but with the right approach, it becomes simple and powerful.

I’ve shown you four methods: using imshow(), using loops, applying scatter plots, and customizing colorbars. Each method works in different scenarios, and you can choose the one that fits your project best.

I use these techniques regularly in my Python projects, especially when preparing reports for USA-based clients. A well-placed colorbar not only improves readability but also makes your plots look professional.

You may also like to read other Matplotlib tutorials:

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.