This can now be done automatically with the release of matplotlib v3.10.0, by setting the axlim_clip=True
argument when plotting in 3D.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-15, 15, 1000)
y = np.ones_like(x)
z = np.exp(-x**2 / 2) / np.sqrt(2 * np.pi)
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax.plot(x, y + 1, z, color='blue')
ax.plot(x, y, z, color='red', axlim_clip=True)
ax.set_xlim(-5, 5)
ax.set_ylim(-1, 4)
plt.show()