1

如何制作一个函数,通过它我可以在 Python 中使用 matplotlib 放大和缩小鼠标滚动事件的图形?

我从这个社区和其他地方给出的例子中得到了帮助。但这对我不起作用。请查看我的代码并找出其中的错误。

import math
import matplotlib
import matplotlib.pyplot as plt
import pylab

def zoom_factory(ax, step = 2.):
    def zoom_fun(event):

        cur_xlim = ax.get_xlim()
        cur_ylim = ax.get_ylim()

        xdata = event.xdata
        ydata = event.ydata

        ax = event.inaxes
        step = event.step
        if event.button == 'up':
            step = -2
        elif event.button == 'down':
            step = 2

        xdata, ydata = event.xdata, event.ydata

        if step >0:
            delx = float(cur_xlim[1] - cur_xlim[0])*step/100
            dely = float(cur_ylim[1] - cur_ylim[0])*step/100

        else:
            delx = float(cur_xlim[1] - cur_xlim[0])*step/(100-step)
            dely = float(cur_ylim[1] - cur_ylim[0])*step/(100-step)

        balx = float(xdata - cur_xlim[0])/(cur_xlim[1] - cur_xlim[0])
        baly = float(ydata - cur_ylim[0])/(cur_ylim[1] - cur_ylim[0])

        cur_xlim[0] = cur_xlim[0] - balx*delx
        cur_xlim[1] = cur_xlim[1] + (1- balx)*delx

        cur_ylim[0] = cur_ylim[1] - baly*dely
        cur_ylim[1] = cur_ylim[1] - (1- baly)*dely

        if xdata is not None:
            ax.set_xlim((cur_xlim[0], cur_xlim[1]))

        if ydata is not None:
            ax.set_ylim((cur_ylim[0], cur_ylim[1]))

        if xdata is not None or ydata is not None:
            event.canvas.draw_idle()

        plt.draw()
        fig = ax.get_figure()

        fig.canvas.mpl_connect('scroll_event', zoom_fun)

        return zoom_fun

def MultiXYPlot(*xy):

    fig, host = plt.subplots()
    fig.subplots_adjust(right = 0.75)

    new = xy[0]

    x = new[0]
    y = new[1]
    x1 = new[2]
    y1 = new[3]

    p1,=host.plot(  x, y, "b-",label = "X0-Y0 plot")
    p2,=host.plot(x1, y1, "r-",label = "X1-Y1 Plot")

    zoom_factory(host, step = 2)

    host.set_xlim(0, 20)
    host.set_ylim(0, 30)
    host.set_xlabel("X0 Axis")
    host.set_ylabel("Y0 Axis")
    host.legend(loc = "upper left")
    plt.show()

x = [2, 4, 6, 8, 9, 10, 12, 15]
y = [0, 3, 5, 6, 8, 9, 10, 15]
x1 = [0, 3, 5, 7, 9, 13, 15, 17]
y1 = [1, 4, 5, 8, 11, 15, 17, 19]
val = [x, y, x1, y1]
MultiXYPlot(val)
4

0 回答 0