问题
I would like to add a single color bar on the right side of the following 2x2 plot.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-np.pi*2, np.pi*2, num=50)
y = np.linspace(-np.pi*2, np.pi*2, num=50)
def fun(x, y, pw1, pw2):
X,Y = np.meshgrid(x, y)
return (X, Y, np.cos(X*Y)**pw1 + np.sin(X+Y)**pw2)
X, Y, f01 = fun(x,y,0,1)
X, Y, f10 = fun(x,y,1,0)
X, Y, f11 = fun(x,y,1,1)
X, Y, f12 = fun(x,y,1,2)
fig1, axs = plt.subplots(nrows=2,ncols=2, figsize=(8,8),sharex='col', sharey='row')
(ax1, ax2), (ax3, ax4) = axs
levels = np.linspace(-2, 2, 10)
cs1 = ax1.contourf(X, Y, f01, levels=levels, cmap=cmap)
ax1.set_ylabel('angle y', fontsize=16)
ax1.tick_params(labelsize=14)
ax1.set_title('Interference level 1', fontsize=14)
ax1.set_aspect('equal')
cs2 = ax2.contourf(X, Y, f10, levels=levels, cmap=cmap)
ax2.set_title('Interference level 2', fontsize=14)
ax2.set_aspect('equal')
cs3 = ax3.contourf(X, Y, f11, levels=levels, cmap=cmap)
ax3.set_ylabel('angle y', fontsize=16)
ax3.set_xlabel('angle x', fontsize=16)
ax3.tick_params(labelsize=14)
ax3.set_title('Interference level 3', fontsize=14)
ax3.set_aspect('equal')
cs4 = ax4.contourf(X, Y, f12, levels=levels, cmap=cmap)
ax4.set_xlabel('angle x', fontsize=16)
ax4.tick_params(labelsize=14)
ax4.set_title('Interference level 4', fontsize=14)
ax4.set_aspect('equal')
plt.tight_layout()
plt.show()
I have been reviewing the solutions of previous question Matplotlib 2 Subplots, 1 Colorbar
.
However, I have four contourf()
subplots, whereas the posted solutions use imshow()
plot.
# im = imshow
print(im)
AxesImage(223.004,36;98.8364x98.8364)
# Axes
print(ax1)
AxesSubplot(0.0896322,0.541995;0.436434x0.408005)
# Contourf
print(cs1)
<matplotlib.contour.QuadContourSet object at 0x17d398940>
I do not know how to apply the previous solutions with the ax
and cs
object of my plot.
回答1:
IIUC, you can just pass axs
into colorbar
:
plt.tight_layout()
plt.colorbar(cs4, ax=axs)
plt.show()
Output:
来源:https://stackoverflow.com/questions/58823901/2x2-contourf-plots-sharing-the-same-colorbar