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()
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!