Recalculate x y values after zoom based on current ylim and xlim in Matplotlib

后端 未结 1 1169
故里飘歌
故里飘歌 2021-01-15 13:14

Dear all i want to recalculate the x y values written in the tick labeling of my figure after i have zoomed in it in such a way that the origin is always at (0,0) and obviou

1条回答
  •  野的像风
    2021-01-15 14:11

    This may not be as easy as it sounds. When changing the limits, you would change the limits, such that the callback runs infinitly, making your window crash.

    I would hence opt for another solution, using a second axes. So let's say you have two axes:

    • ax2 is the axes to plot to. But is has no frame and no ticklabels. This is the axes you can change the limits with.
    • ax is empty. It initially has the same limits as ax2. And it will show the ticklabels.

    Once you zoom in on ax2 the callback function can change the limits of ax to your liking. This is then what is shown on the screen.

    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]
    
    # ax is empty
    fig, ax = plt.subplots()
    ax.set_navigate(False)
    # ax2 will hold the plot, but has invisible labels
    ax2 = fig.add_subplot(111,zorder=2)
    ax2.scatter(x_seq, y_seq)
    ax2.axis("off")
    
    ax.set_xlim(ax2.get_xlim())
    ax.set_ylim(ax2.get_ylim())
    
    #
    # Declare and register callbacks
    def on_lims_change(axes):
        # change limits of ax, when ax2 limits are changed.
        a=ax2.get_xlim()
        ax.set_xlim(0, a[1]-a[0])
        a=ax2.get_ylim()
        ax.set_ylim(0, a[1]-a[0])
    
    ax2.callbacks.connect('xlim_changed', on_lims_change)
    ax2.callbacks.connect('ylim_changed', on_lims_change)
    
    # Show
    plt.show()
    

    0 讨论(0)
提交回复
热议问题