Matplotlib事件和重新绘制

时间:2013-01-15 11:32:00

标签: python matplotlib

我希望能够创建绘图,根据绘图显示的内容按一个或另一个按钮,然后绘制以下对象。但是,我遇到了一些麻烦:似乎我不能让它“等待”直到按下一个按钮。另外,我想知道是否可以将一些参数传递给press_event,就像保存某些东西的路径一样。

如果程序有帮助,这是程序的方案。非常感谢提前!

# event definition
def ontype(event):
    if event.key == '1':
        do stuff 1
        plt.savefig(...)
        plt.clf()
    elif event.key == '2':
        do stuff 2
        plt.savefig(...)
        plt.clf()
    elif event.key == '3':
        do stuff 3
        plt.savefig(...)
        plt.clf()

# main program
...stuff
create figure
plt.show()
plt.gcf().canvas.mpl_connect('key_press_event',ontype)

1 个答案:

答案 0 :(得分:3)

您必须在plt.gcf().canvas.mpl_connect('key_press_event',ontype)之前致电plt.show()。在非交互模式下,执行等待plt.show(),直到绘图窗口关闭。

import pylab as plt

# event definition
def ontype(event):
    if event.key == '1':
        print "1"
    elif event.key == '2':
        print "2"
    elif event.key == '3':
        print "3"

# main program
plt.plot([1,6,3,8,7])
plt.gcf().canvas.mpl_connect('key_press_event',ontype)
plt.show()

或者,将样本plt.show()替换为plt.ion(),以启用交互模式。但这取决于您的具体需求,您更喜欢哪种解决方案。

修改

使用Tkinter的新示例

import random
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure

try:
    import Tkinter as Tk
except ImportError:
    import tkinter as Tk
import tkMessageBox

class PlotClassifier(Tk.Tk):
    def __init__(self, plot_generator, arguments, classes, classification_callback, *args, **kwargs):
        Tk.Tk.__init__(self, *args, **kwargs)
        self.title("Plot classifier, working on %i plots" % len(arguments))
        #self.label = Tk.Label(text="Plot classifier, working on %i plots" % len(arguments))
        #self.label.pack(padx=10, pady=10)
        self._plot_generator = plot_generator
        self._arguments = arguments
        self._classes = [str(x) for x in classes]
        self._classification_callback = classification_callback
        self._setup_gui()

    def _setup_gui(self):
        #self.columnconfigure(0, minsize=100, weight=2)
        #self.columnconfigure(1, minsize=500, weight=8)
        f = Figure()
        self._ax = f.add_subplot(111)
        buttons_frame = Tk.Frame(self)
        buttons_frame.pack(side=Tk.TOP, fill=Tk.BOTH, expand=True)
        buttons_class = []
        for i, cls in enumerate(self._classes):
            buttons_class.append(Tk.Button(master=buttons_frame, text=cls, 
                                           command=lambda x=i: self.button_classification_callback(self._current_args, x)))
            buttons_class[-1].pack(side=Tk.LEFT)
        button_quit = Tk.Button(master=buttons_frame, text='Quit', command=self.destroy)
        button_quit.pack(side=Tk.RIGHT) #.grid(row=0,column=0)

        self._canvas = FigureCanvasTkAgg(f, master=self)
        self._canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) #.grid(row=0, column=1, rowspan=3) #
        self._canvas.show()

        toolbar = NavigationToolbar2TkAgg( self._canvas, self )
        toolbar.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) #.grid(row=3, column=1) #
        toolbar.update()

    def button_classification_callback(self, args, class_idx):
        self._classification_callback(args, self._classes[class_idx])
        self.classify_next_plot()

    def classify_next_plot(self):
        try:
            self._current_args = self._arguments.pop(0)
            self._ax.cla()
            self._plot_generator(self._ax, *self._current_args)
            self._canvas.draw()
        except IndexError:
            tkMessageBox.showinfo("Complete!", "All plots were classified")
            self.destroy()        

def create_plot(ax, factor):
    ax.plot([(i*factor) % 11 for i in range(100)])

def announce_classification(arguments, class_):
    print arguments, class_

if __name__ == "__main__":
    classes = ["Class %i"%i for i in range(1, 6)]
    arguments_for_plot = [[random.randint(1,10)] for x in range(10)]
    root = PlotClassifier(create_plot, arguments_for_plot, classes, classification_callback=announce_classification)
    root.after(50, root.classify_next_plot)
    root.mainloop()

该类作为参数:  *回调创建每个情节  *每个要生成的绘图的参数列表列表(可能每个都是一个空列表)  *一个类名列表。对于每个类,都会创建一个按钮  *每次执行分类时调用的回调

任何反馈都将不胜感激。

* 编辑2 * 对于您的评论,略有修改版本。对于循环的每次迭代,都会打开一个新窗口

import random
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure

try:
    import Tkinter as Tk
except ImportError:
    import tkinter as Tk
import tkMessageBox

class PlotClassifier(Tk.Tk):
    def __init__(self, plot_generator, arguments, classes, *args, **kwargs):
        Tk.Tk.__init__(self, *args, **kwargs)
        self.title("Plot classifier")
        self._plot_generator = plot_generator
        self._arguments = arguments
        self._classes = [str(x) for x in classes]
        self.class_ = None
        self._setup_gui()

    def _setup_gui(self):
        #self.columnconfigure(0, minsize=100, weight=2)
        #self.columnconfigure(1, minsize=500, weight=8)
        f = Figure()
        self._ax = f.add_subplot(111)
        buttons_frame = Tk.Frame(self)
        buttons_frame.pack(side=Tk.TOP, fill=Tk.X, expand=True)
        buttons_class = []
        for i, cls in enumerate(self._classes):
            buttons_class.append(Tk.Button(master=buttons_frame, text=cls, 
                                           command=lambda x=i: self.button_classification_callback(x)))
            buttons_class[-1].pack(side=Tk.LEFT)
        button_quit = Tk.Button(master=buttons_frame, text='Quit', command=self.destroy)
        button_quit.pack(side=Tk.RIGHT) #.grid(row=0,column=0)

        self._canvas = FigureCanvasTkAgg(f, master=self)
        self._canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) #.grid(row=0, column=1, rowspan=3) #
        self._canvas.show()

        toolbar = NavigationToolbar2TkAgg( self._canvas, self )
        toolbar.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) #.grid(row=3, column=1) #
        toolbar.update()

    def button_classification_callback(self, class_idx):
        self.class_ = self._classes[class_idx]
        self.destroy()

    def classify_plot(self):
        self._ax.cla()
        self._plot_generator(self._ax, *self._arguments)
        self._canvas.draw()
        self.mainloop()
        return self.class_

def create_plot(ax, factor):
    ax.plot([(i*factor) % 11 for i in range(100)])


if __name__ == "__main__":
    classes = ["Class %i"%i for i in range(1, 6)]
    arguments_for_plot = [[random.randint(1,10)] for x in range(10)]
    for args in arguments_for_plot:
        classifier = PlotClassifier(create_plot, args, classes)
        class_ = classifier.classify_plot()
        print args, class_
        if class_ is None:
            break

这有助于适应你自己的for循环,但你仍然需要在创建GUI之后给出一个函数来进行绘图。