Matplotlib:缩放后找出xlim和ylim

发布于 2021-01-29 19:34:07

您肯定知道一种快速方法,在放大后如何追踪图形的极限?我想精确地知道坐标,以便可以使用ax.set_xlim和复制图形ax.set_ylim。我正在使用标准的qt4agg后端。

编辑:我知道我可以使用光标找出上下角处的两个位置,但是也许有正式的方法可以做到这一点?

关注者
0
被浏览
98
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    matplotlib有一个事件处理API,您可以使用它来挂接您所指代的操作。“事件处理”页面提供了事件API的概述,并且在“轴”页面上(非常)简短地提到了x和y极限事件。

    Axes实例通过作为实例的callbacks属性支持回调CallbackRegistry。您可以连接的事件为xlim_changedylim_changed并且回调将在实例func(ax)所在的位置调用。ax``Axes

    在您的方案中,您想在Axes对象的xlim_changedylim_changed事件上注册回调函数。每当用户缩放或移动视口时,将调用这些函数。

    这是一个最小的工作示例:

    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()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看