我试图将通过 2D 等值线图的 1D 路径作为等值线图下方的单独图包含在内。理想情况下,它们将具有共享且对齐的 X 轴,以引导读者了解绘图的特征,并包含颜色条图例。
我做了这个最小的例子来展示我的尝试和问题。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
# Generating dummy data
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z = np.outer(np.cos(y), np.cos(3*x))
# Configure the plot
gs = gridspec.GridSpec(2,1,height_ratios=[4,1])
fig = plt.figure()
cax = fig.add_subplot(gs[0])
# Contour plot
CS = cax.contourf(X, Y, Z)
# Add line illustrating 1D path
cax.plot([-3,3],[0,0],ls="--",c='k')
cbar = fig.colorbar(CS)
# Simple linear plot
lax = fig.add_subplot(gs[1],sharex=cax)
lax.plot(x, np.cos(3*x))
lax.set_xlim([-3,3])
plt.show()
结果如下:
显然,子图区域中包含的颜色条偏离了对齐。
最佳答案
在编写这个问题的过程中,我找到了一种解决方法,将颜色条作为它自己的轴,这样网格规范现在是一个 2x2 子图网格。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z = np.outer(np.cos(y), np.cos(3*x))
# Gridspec is now 2x2 with sharp width ratios
gs = gridspec.GridSpec(2,2,height_ratios=[4,1],width_ratios=[20,1])
fig = plt.figure()
cax = fig.add_subplot(gs[0])
CS = cax.contourf(X, Y, Z)
cax.plot([-3,3],[0,0],ls="--",c='k')
lax = fig.add_subplot(gs[2],sharex=cax)
lax.plot(x, np.cos(3*x))
lax.set_xlim([-3,3])
# Make a subplot for the colour bar
bax = fig.add_subplot(gs[1])
# Use general colour bar with specific axis given.
cbar = plt.colorbar(CS,bax)
plt.show()
This gives the desired result.
如果有任何更优雅的解决方案,我仍然会感兴趣。
关于python - 将 Matplotlib 轮廓 2D 和 1D 图中的 X 轴与颜色条图例对齐并共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48966920/