如何激活matplotlibs缩放至矩形的功能?

时间:2019-01-21 11:18:03

标签: python matplotlib

在tkinter画布上,我添加了matplotlib导航工具栏,并绘制了几行要使用函数进行选择和修改的行。我还希望能够放大画布并选择线条,而不必每次执行定义的功能时都激活和禁用“缩放到矩形”。有没有办法同时使用matplotlib的zoom功能和我定义的功能?

import sys
if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
    import tkinter as Tk
from matplotlib.figure import Figure
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk

root = Tk.Tk()
fig = Figure()
ax = fig.add_subplot(111)

canvas = FigureCanvasTkAgg(fig, master=root)
nav = NavigationToolbar2Tk(canvas, root)
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

x = np.arange(10)
ax.plot(x, x, picker=True)
ax.plot(x, 2 * x, picker=True)
ax.plot(x, 3 * x, picker=True)
ax.plot(x, 4 * x, picker=True)

def _onPick(event):
    thisline = event.artist
    thisline.set_linewidth(5)
    fig.canvas.draw()

fig.canvas.callbacks.connect('pick_event', _onPick)

root.mainloop()

1 个答案:

答案 0 :(得分:1)

您可以连接"button_press_event"并了解点击是否发生在线条所覆盖的地方。这比使用内置选择器要复杂得多。

x = np.arange(10)
ax.plot(x, x, picker=6)
ax.plot(x, 2 * x, picker=6)
ax.plot(x, 3 * x, picker=15)
ax.plot(x, 4 * x, picker=1)

def _onPick(event):
    update = False
    if event.inaxes == ax:
        for line in ax.lines:
             if line.get_picker():
                 cont, ind = line.contains(event)
                 if cont:
                     line.set_linewidth(5)
                     update=True
    if update:
        fig.canvas.draw_idle()

fig.canvas.callbacks.connect('button_press_event', _onPick)

请注意,我在此处重新定义了选择器,以在其中声明半径,这可能对确保一个人实际击中一条线很有帮助。