matplotlib has an event handling API you can use to hook in to actions like the ones you’re referring to. The Event Handling page gives an overview of the events API, and there’s a (very) brief mention of the x- and y- limits events on the Axes page.
The
Axes
instance supports callbacks through a callbacks attribute which is aCallbackRegistry
instance. The events you can connect to arexlim_changed
andylim_changed
and the callback will be called withfunc(ax)
whereax
is theAxes
instance.
In your scenario, you’d want to register callback functions on the Axes
object’s xlim_changed
and ylim_changed
events. These functions will get called whenever the user zooms or shifts the viewport.
Here’s a minimum working example:
Python 2
import matplotlib.pyplot as plt
#
# Some toy data
x_seq = [x / 100.0 for x in xrange(1, 100)]
y_seq = [x**2 for x in x_seq]
#
# Scatter plot
fig, ax = plt.subplots(1, 1)
ax.scatter(x_seq, y_seq)
#
# Declare and register callbacks
def on_xlims_change(event_ax):
print "updated xlims: ", event_ax.get_xlim()
def on_ylims_change(event_ax):
print "updated ylims: ", event_ax.get_ylim()
ax.callbacks.connect('xlim_changed', on_xlims_change)
ax.callbacks.connect('ylim_changed', on_ylims_change)
#
# Show
plt.show()
Python 3
import matplotlib.pyplot as plt
#
# Some toy data
x_seq = [x / 100.0 for x in range(1, 100)]
y_seq = [x**2 for x in x_seq]
#
# Scatter plot
fig, ax = plt.subplots(1, 1)
ax.scatter(x_seq, y_seq)
#
# Declare and register callbacks
def on_xlims_change(event_ax):
print("updated xlims: ", event_ax.get_xlim())
def on_ylims_change(event_ax):
print("updated ylims: ", event_ax.get_ylim())
ax.callbacks.connect('xlim_changed', on_xlims_change)
ax.callbacks.connect('ylim_changed', on_ylims_change)
#
# Show
plt.show()