Matplotlib缩放级别在按键事件时后退

2024-09-30 04:37:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在matplotlib图形中选择一个区域,方法是放大该图形,然后按下“c”键,获取当前轴限制

但是,在按键事件中,图形会自动将缩放级别后退一步。因此,当调用回调函数时,它会获取上一个缩放级别的轴限制(即,如果我只缩放了一次,则为“主”限制;如果我缩放了多次,则为第二个到最后一个缩放级别)

我认为获取轴限制可能会干扰上述限制,但在回调函数中不做任何操作也没有什么区别,图形仍然会缩小

为什么会这样,如何避免呢

下面,最小代码:运行此操作,在图形上缩放一次,按c,回调将打印-0.35000000000000003 7.35 -0.25 5.25,与初始图形设置相对应,无论您选择的缩放是什么

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)

Tags: the函数selfevent图形getmatplotlibdef
1条回答
网友
1楼 · 发布于 2024-09-30 04:37:32

答案是由于c键是interactive navigation热键的一部分

解决方案很简单:重新配置与back相关的keymap

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)

相关问题 更多 >

    热门问题