How do I make a function through which I can zoom in and zoom out into a graph on a mouse scroll event using matplotlib in Python?
I have taken help from the examples given on this community and from some other place. But this not working for me. Please look into my code and find the fault in it.
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)