问题
I want to choose a zone in my matplotlib figure by zooming into the figure then, when the key 'c' is pressed, getting the current axes limits.
However, on key press event, the figure automatically rolls back the zoom level one step back. So when the callback function is called, it gets the axes limit for the previous zoom level (ie, "home" limits if I have zoomed only once, or the second-to-last zoom level if I have zoomed more than once).
I thought maybe getting the axes limits interferes with said limits, but doing nothing in the callback function makes no difference, the figure still gets zoomed back out.
Why is that, and how to avoid it??
Below, minimal code: run this, zoom once on the figure, press c, and the callback will print -0.35000000000000003 7.35 -0.25 5.25
, corresponding to the initial figure setup, no matter what your chosen zoom is.
import matplotlib.pyplot as plt
class CropZoneFinder:
def __init__(self, fig):
# Prepare the graphics
self.figure = fig
self.figure.canvas.mpl_connect('key_press_event', self)
plt.show()
def __call__(self, event):
"""
This is the callback function used by matplotlib figure to handle input
"""
if event.key == 'c':
xlims = self.figure.get_axes()[0].get_xlim()
ylims = self.figure.get_axes()[0].get_ylim()
xleft = xlims[0]
xright = xlims[1]
yleft = ylims[0]
yright = ylims[1]
print(xleft, xright, yleft, yright)
if __name__ == "__main__":
fig, ax = plt.subplots()
ax.plot([0,1,2,3,4,5,4,3])
cropfinder = CropZoneFinder(fig)
回答1:
The answer is due to the key c
being part of the interactive navigation hotkey.
The solution is simple: re-configure the keymap related to back.
import matplotlib as mpl
...
if __name__ == "__main__":
fig, ax = plt.subplots()
mpl.rcParams["keymap.back"] = ['left', 'backspace']
ax.plot([0,1,2,3,4,5,4,3])
cropfinder = CropZoneFinder(fig)
来源:https://stackoverflow.com/questions/63169715/matplotlib-zoom-level-stepping-back-on-key-press-event