The code below produces a simple plot in which the top and right spines are hidden, and in which the left and bottom spines have been set along the y-axis and x-axis, respectively. If I pan around in the plot, then the left and bottom spines remain visible even if they lie outside of the coordinates specified by ax.get_xlim() and ax.get_ylim(), which I would like not to happen. Essentially, I would like something like adjust_spines(ax) to be evaluated continuously while paning, without having to set fig.subplots_adjust(left=0, bottom=0, right=1, top=1). Is this possible?
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
fig.subplots_adjust(left=0.2, bottom=0.2, right=0.9, top=0.8)
ax.spines[['right', 'top']].set_visible(False)
ax.grid(linestyle='--')
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
x = np.linspace(-3, 5)
ax.plot(x, x/2)
# The left spine is not clipping correctly in the x-direction,
# and the bottom spine is not clipping correctly in the y-direction.
ax.spines['left'].set(clip_on=True)
ax.spines['bottom'].set(clip_on=True)
# Should happen continuously:
def adjust_spines(axis):
x_min, x_max = axis.get_xlim()
y_min, y_max = axis.get_ylim()
axis.spines['left'].set_visible(x_min <= 0 <= x_max)
axis.spines['bottom'].set_visible(y_min <= 0 <= y_max)
plt.show()
What I see immediately after code is run:

What I see after paning towards the bottom left corner (notice the white void):

What I have tried:
I have tried modifying the clipping properties of the spines directly as shown in the code, but this does not work. I also tried setting the spines clip_box equal to the ax.get_position() Bbox, but this does not work either. As far as I can tell from reading the spine docs matplotlib spines, I cannot just pass a function to the spines that constantly evaluates if the spines should be shown or not.
What I was expecting:
To be able to hide the spines if they are outside of the axes limits.
Not sure why you would want to do this, especially since you will lose information about where you are on the grid if you are far from the origin, but here is a possible solution. It involves a few hacks to keep the grid visible while making the ticks (nearly) invisible.