2x2 Contourf图共享相同的颜色条

时间:2019-11-12 17:37:33

标签: python matplotlib colorbar contourf

我想在下面的2x2图的右侧添加单个颜色条。

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

enter image description here

我一直在审查上一个问题 Matplotlib 2 Subplots, 1 Colorbar 的解决方案。 但是,我有四个contourf()子图,而发布的解决方案使用imshow()图。

# 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>

我不知道如何对情节的axcs对象应用先前的解决方案。

1 个答案:

答案 0 :(得分:1)

IIUC,您只需将axs传递到colorbar

plt.tight_layout()
plt.colorbar(cs4, ax=axs)
plt.show()

输出:

enter image description here