Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to plot a pcolor colorbar in a different subplot in Matplotlib?
To plot a pcolor colorbar in a different subplot in Matplotlib, you can create multiple subplots and add individual colorbars to each one using the fig.colorbar() method.
Basic Setup
First, let's understand the key components needed ?
- Create a figure with multiple subplots using
plt.subplots() - Generate pseudocolor plots with
pcolormesh() - Add colorbars using
fig.colorbar()with specific axis references - Use different colormaps for visual distinction
Example: Multiple Subplots with Individual Colorbars
import matplotlib.pyplot as plt
import numpy as np
# Set figure size
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True
# Create 2x2 subplot grid
fig, axs = plt.subplots(2, 2)
# Define different colormaps
colormaps = ['plasma', 'copper']
# Create pcolor plots with colorbars
for col in range(2):
for row in range(2):
ax = axs[row, col]
# Generate random data scaled by column
data = np.random.random((20, 20)) * (col + 1)
# Create pcolormesh plot
pcm = ax.pcolormesh(data, cmap=colormaps[col])
# Add colorbar to current subplot
fig.colorbar(pcm, ax=ax)
# Set subplot title
ax.set_title(f'Subplot ({row+1}, {col+1}) - {colormaps[col]}')
plt.tight_layout()
plt.show()
Alternative: Shared Colorbar Across Subplots
You can also create a single colorbar that applies to multiple subplots ?
import matplotlib.pyplot as plt
import numpy as np
# Create figure and subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
# Generate sample data
data1 = np.random.random((15, 15)) * 10
data2 = np.random.random((15, 15)) * 10
# Create pcolormesh plots with same colormap
pcm1 = ax1.pcolormesh(data1, cmap='viridis', vmin=0, vmax=10)
pcm2 = ax2.pcolormesh(data2, cmap='viridis', vmin=0, vmax=10)
# Add titles
ax1.set_title('Dataset 1')
ax2.set_title('Dataset 2')
# Create shared colorbar
fig.colorbar(pcm1, ax=[ax1, ax2], shrink=0.8, location='bottom')
plt.tight_layout()
plt.show()
Key Parameters
| Parameter | Description | Example Value |
|---|---|---|
ax |
Subplot(s) to attach colorbar to |
ax=ax or ax=[ax1, ax2]
|
cmap |
Colormap for the plot |
'plasma', 'viridis'
|
shrink |
Scale factor for colorbar size |
0.8 (80% of default size) |
location |
Colorbar position |
'right', 'bottom'
|
Conclusion
Use fig.colorbar(pcm, ax=ax) to add individual colorbars to specific subplots. For shared colorbars across multiple subplots, pass a list of axes to the ax parameter.
Advertisements
