you for sure know a fast way how I can track down the limits of my figure after having zoomed in? I would like to know the coordinates precisely so I can reproduce the figure with ax.set_xlim
and ax.set_ylim
.
I am using the standard qt4agg backend.
edit: I know I can use the cursor to find out the two positions in the lower and upper corner, but maybe there is formal way to do that?
The xlim() function in pyplot module of matplotlib library is used to get or set the x-limits of the current axes. Parameters: This method accept the following parameters that are described below: left: This parameter is used to set the xlim to left. right: This parameter is used to set the xlim to right.
Press the right mouse button to zoom, dragging it to a new position. The x axis will be zoomed in proportionately to the rightward movement and zoomed out proportionately to the leftward movement. The same is true for the y axis and up/down motions.
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()
print ax.get_xlim(), ax.get_ylim()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With