Reputation: 155
I get the wrong color scheme and range when I try to plot colorbar with contourf. It works well with pcolormesh. I'm aiming to only use 1 colorbar for all the subplots
fig = plt.figure(figsize=(9,8))
gs = gridspec.GridSpec(nrows=1, ncols=3)
color = plt.get_cmap('PRGn')
ax0 = plt.subplot(gs[0, 0])
ax0.contourf(x, y, z1, cmap=color)
ax1 = plt.subplot(gs[0, 1])
ax1.contourf(x, y, z2, cmap=color)
ax2 = plt.subplot(gs[0, 2])
ax2.contourf(x, y, z3, cmap=color)
# colorbar
im = plt.gca().get_children()[0]
cax = fig.add_axes([.918, 0.175, 0.025, 0.4])
cb = fig.colorbar(im, cax=cax)
Thank you
Upvotes: 0
Views: 2596
Reputation: 80319
The easiest is to store the result of contourf
in a variable to pass to plt.colorbar
.
Note that for the 3 plots to use the same colorbar, the limits need to be the same for each. Default, vmin
and vmax
are set to the minimum and maximum of the given z-array. To get them equal for the 3 plots, one could set them to the global minimum and maximum.
Here is an example (using the modern way to define the subplots):
import numpy as np
import matplotlib.pyplot as plt
fig, (ax0, ax1, ax2) = plt.subplots(nrows=1, ncols=3, figsize=(9, 8))
# create some dummy data, where z1, z2 and z3 possibly have different ranges
x, y = np.meshgrid(np.linspace(0, 4, 20), np.linspace(300, 850, 20))
z1 = np.cos(x) + np.sin(y / 100)
z2 = np.cos(x) + np.sin(y / 100) + 0.2
z3 = np.cos(x) + np.sin(y / 100) + 0.5
vmin = min(z1.min(), z2.min(), z3.min())
vmax = max(z1.max(), z2.max(), z3.max())
cmap = plt.get_cmap('PRGn')
contour_z1 = ax0.contourf(x, y, z1, cmap=cmap, vmin=vmin, vmax=vmax)
contour_z2 = ax1.contourf(x, y, z2, cmap=cmap, vmin=vmin, vmax=vmax)
contour_z3 = ax2.contourf(x, y, z3, cmap=cmap, vmin=vmin, vmax=vmax)
# colorbar
cax = fig.add_axes([.918, 0.175, 0.025, 0.4])
cb = fig.colorbar(contour_z1, cax=cax)
plt.show()
Upvotes: 4