Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

python - Matplotlib: Finding out xlim and ylim after zoom

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 a CallbackRegistry instance. The events you can connect to are xlim_changed and ylim_changed and the callback will be called with func(ax) where ax is the Axes 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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...