I am trying to include a 1D path through a 2D contour plot as a separate plot below the contour plot. Ideally these will have a shared and aligned X axis to guide the reader through the features of the plot, and will include a colour bar legend.
I have made this minimal example to show my attempt and the problem.
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()
This gives the following image as a result:
Clearly the colour bar being included in the subplot area is throwing off the align.