Matplotlib图用滚轮缩放 [英] Matplotlib plot zooming with scroll wheel
本文介绍了Matplotlib图用滚轮缩放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当光标悬停在matplotlib图上时,是否可以将滚轮绑定到放大/缩小?
Is it possible to bind the scroll wheel to zoom in/out when the cursor is hovering over a matplotlib plot?
推荐答案
这应该有效.滚动时,它将使图形重新居中于指针的位置.
This should work. It re-centers the graph on the location of the pointer when you scroll.
import matplotlib.pyplot as plt
def zoom_factory(ax,base_scale = 2.):
def zoom_fun(event):
# get the current x and y limits
cur_xlim = ax.get_xlim()
cur_ylim = ax.get_ylim()
cur_xrange = (cur_xlim[1] - cur_xlim[0])*.5
cur_yrange = (cur_ylim[1] - cur_ylim[0])*.5
xdata = event.xdata # get event x location
ydata = event.ydata # get event y location
if event.button == 'up':
# deal with zoom in
scale_factor = 1/base_scale
elif event.button == 'down':
# deal with zoom out
scale_factor = base_scale
else:
# deal with something that should never happen
scale_factor = 1
print event.button
# set new limits
ax.set_xlim([xdata - cur_xrange*scale_factor,
xdata + cur_xrange*scale_factor])
ax.set_ylim([ydata - cur_yrange*scale_factor,
ydata + cur_yrange*scale_factor])
plt.draw() # force re-draw
fig = ax.get_figure() # get the figure of interest
# attach the call back
fig.canvas.mpl_connect('scroll_event',zoom_fun)
#return the function
return zoom_fun
假设您有一个轴对象ax
ax.plot(range(10))
scale = 1.5
f = zoom_factory(ax,base_scale = scale)
可选参数base_scale
允许您将比例因子设置为所需的比例因子.
The optional argument base_scale
allows you to set the scale factor to be what ever you want.
确保周围保留f
的副本.回调使用弱引用,因此,如果不保留f
的副本,则可能会被垃圾回收.
make sure you keep a copy of f
around. The call back uses a weak-ref so if you do not keep a copy of f
it might be garbage collected.
写完此答案后,我认为这实际上很有用,并将其放在要点
After writing this answer I decided this actually quite useful and put it in a gist
这篇关于Matplotlib图用滚轮缩放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文