基于Tkinter和matplotlib的交互式绘图

时间:2012-04-03 16:54:29

标签: python user-interface matplotlib tkinter

亲爱的编程共同美,

我正在尝试基于Tkinter和pylab.plot执行“交互式绘图”以绘制1D值。 abssissa是1D numpy数组x,ordonates值在多维数组Y中,例如。

import numpy
x = numpy.arange(0.0,3.0,0.01)
y = numpy.sin(2*numpy.pi*x)
Y = numpy.vstack((y,y/2))

我想根据x显示y或y / 2(Y矩阵的元素),并在左右两个按钮之间进行切换(为了更复杂的情况)。通常我会创建一些如下的函数来绘制图形。

import pylab
def graphic_plot(n):
    fig = pylab.figure(figsize=(8,5))
    pylab.plot(x,Y[n,:],'x',markersize=2)
    pylab.show()

要添加两个按钮来更改n参数的值,我试过这个没有成功:

import Tkinter
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class App:
def __init__(self,master):
    # Create a container
    frame = Tkinter.Frame(master)
    frame.pack()
    # Create 2 buttons
    self.button_left = Tkinter.Button(frame,text="<",command=self.decrease)
    self.button_left.pack(side="left")
    self.button_right = Tkinter.Button(frame,text=">",command=self.increase)
    self.button_right.pack(side="left")
    self.canvas = FigureCanvasTkAgg(fig,master=self)
    self.canvas.show()
def decrease(self):
    print "Decrease"
def increase(self):
    print "Increase"
root = Tkinter.Tk()
app = App(root)
root.mainloop()

有人可以帮助我了解如何执行此类功能吗?非常感谢。

1 个答案:

答案 0 :(得分:5)

要更改线条的y值,请保存绘制时返回的对象(line, = ax.plot(...)),然后使用line.set_ydata(...)。要重绘绘图,请使用canvas.draw()

作为基于代码的更完整的示例:

import Tkinter
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

class App:
    def __init__(self, master):
        # Create a container
        frame = Tkinter.Frame(master)
        # Create 2 buttons
        self.button_left = Tkinter.Button(frame,text="< Decrease Slope",
                                        command=self.decrease)
        self.button_left.pack(side="left")
        self.button_right = Tkinter.Button(frame,text="Increase Slope >",
                                        command=self.increase)
        self.button_right.pack(side="left")

        fig = Figure()
        ax = fig.add_subplot(111)
        self.line, = ax.plot(range(10))

        self.canvas = FigureCanvasTkAgg(fig,master=master)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1)
        frame.pack()

    def decrease(self):
        x, y = self.line.get_data()
        self.line.set_ydata(y - 0.2 * x)
        self.canvas.draw()

    def increase(self):
        x, y = self.line.get_data()
        self.line.set_ydata(y + 0.2 * x)
        self.canvas.draw()

root = Tkinter.Tk()
app = App(root)
root.mainloop()