我想生成一个图形,在左侧显示二维数据,在右侧显示所述数据的垂直切片。
我使用以下 MWE 成功做到了:
import matplotlib.pyplot as plt
import numpy as np
nz = 66
nx = 130
ny = 230
h = 70
ensemble_size = 50
x = np.array([ix*h / 1000 for ix in range(nx)])
y = np.array([iy*h / 1000 for iy in range(ny)])
z = np.array([iz*h / 1000 for iz in range(nz)])
Y, Z = np.meshgrid(y, z, indexing='ij')
vp_min = 1400
vp_max = 3350
p_max = 1200
ix = 42
iy = 81
vp = (vp_max - vp_min)*np.random.rand(nz*nx*ny, ensemble_size) + vp_min
vp_mean = np.mean(vp, axis=1).reshape(nz*nx*ny, 1)
########################################################################
fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True)
ax1.pcolor(Y, Z, vp_mean.reshape(nz, nx, ny, order='F')[:,ix,:].T, cmap="jet", vmin=vp_min, vmax=vp_max)
ax1.plot(iy*h*np.ones(nz) / 1000, z, "k--")
ax1.set_ylabel(r'Depth ($km$)')
ax1.set_xlabel(r'Y ($km$)')
ax1.set_aspect('equal')
lines = []
for e in range(ensemble_size):
lines.append( ax2.plot(vp[:,e].reshape(nz, nx, ny, order='F')[:,ix,iy], z, "b", alpha=0.25, label="models") )
lines.append( ax2.plot(vp_mean.reshape(nz, nx, ny, order='F')[:,ix,iy], z, "r", alpha=1.0, label="average model") )
plt.setp(lines[1:ensemble_size], label="_")
ax2.set_xlabel(r'$V_p$ ($m/s$)')
ax2.invert_yaxis()
ax2.legend()
########################################################################
plt.savefig("log_" + str(ix) + "_" + str(iy) + ".pdf", bbox_inches='tight')
plt.show(block=False)
plt.close("all")
编辑 我也尝试过使用
fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True, gridspec_kw={'width_ratios':[5, 1]})
...
ax1.set_aspect(1)
除了手动调整图形大小之外,第二种方法是使用作为父级的子级的 inset_axes 。 您甚至可以设置两者之间的共享,但如果您想要的话,您必须删除刻度标签:
fig, ax1 = plt.subplots(constrained_layout=True)
ax1.pcolor(Y, Z, vp_mean.reshape(nz, nx, ny, order='F')[:,ix,:].T, cmap="jet", vmin=vp_min, vmax=vp_max)
ax1.plot(iy*h*np.ones(nz) / 1000, z, "k--")
ax1.set_ylabel(r'Depth ($km$)')
ax1.set_xlabel(r'Y ($km$)')
ax1.set_aspect('equal')
ax2 = ax1.inset_axes([1.05, 0, 0.3, 1], transform=ax1.transAxes)
ax1.sharey(ax2)
lines = []
for e in range(ensemble_size):
lines.append( ax2.plot(vp[:,e].reshape(nz, nx, ny, order='F')[:,ix,iy], z, "b", alpha=0.25, label="models") )
lines.append( ax2.plot(vp_mean.reshape(nz, nx, ny, order='F')[:,ix,iy], z, "r", alpha=1.0, label="average model") )
plt.setp(lines[1:ensemble_size], label="_")
ax2.set_xlabel(r'$V_p$ ($m/s$)')
这样做的优点是,即使您缩放第一个轴,第二个轴也将始终存在。