Home > Backend Development > Python Tutorial > How to Create a Unified Colorbar for Multiple Matplotlib Subplots?

How to Create a Unified Colorbar for Multiple Matplotlib Subplots?

Susan Sarandon
Release: 2024-12-20 07:49:09
Original
388 people have browsed it

How to Create a Unified Colorbar for Multiple Matplotlib Subplots?

Achieving a Unified Colorbar for Multiple Subplots

Creating subplots with a shared y-axis is a common task in Matplotlib. However, adding a single colorbar to multiple subplots can lead to inconsistencies and misalignment.

To create a colorbar that spans all subplots, we introduce an additional subplot dedicated to displaying the colorbar. This subplot has its axes turned off to prevent it from displaying any actual data.

Here's a modified code snippet based on the original question:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
fig.subplots_adjust(wspace=0, hspace=0)

# Subplot 1
ax1 = fig.add_subplot(1, 3, 1)
plt.imshow(data1, extent=(-2, 2, -2, 2))  # Placeholder data

# Subplot 2
ax2 = fig.add_subplot(1, 3, 2, sharey=ax1)
plt.imshow(data2, extent=(-2, 2, -2, 2))  # Placeholder data

# Colorbar subplot
ax3 = fig.add_subplot(1, 3, 3)
ax3.axis('off')
cbar = plt.colorbar(ax=ax2)

plt.show()
Copy after login

By placing the colorbar in its own subplot, we ensure that it remains independent of the data plots and maintains a consistent size. The call to subplots_adjust helps to make room for the colorbar, preventing it from overlapping with the subplots.

This technique allows for a clean and standardized display of data across multiple subplots, providing a better visual representation of the data and making it easier to compare values.

The above is the detailed content of How to Create a Unified Colorbar for Multiple Matplotlib Subplots?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template