Create dynamic updated graph with Python

前端 未结 5 1378
情歌与酒
情歌与酒 2021-02-04 19:25

I need your help to write a script in Python that will take dynamically changed data, the source of data is not matter here, and display graph on the screen.

I know how

5条回答
  •  猫巷女王i
    2021-02-04 19:48

    Here is a class I wrote that handles this issue. It takes a matplotlib figure that you pass to it and places it in a GUI window. Its in its own thread so that it stays responsive even when your program is busy.

    import Tkinter
    import threading
    import matplotlib
    import matplotlib.backends.backend_tkagg
    
    class Plotter():
        def __init__(self,fig):
            self.root = Tkinter.Tk()
            self.root.state("zoomed")
    
            self.fig = fig
            t = threading.Thread(target=self.PlottingThread,args=(fig,))
            t.start()
    
        def PlottingThread(self,fig):     
            canvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(fig, master=self.root)
            canvas.show()
            canvas.get_tk_widget().pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)
    
            toolbar = matplotlib.backends.backend_tkagg.NavigationToolbar2TkAgg(canvas, self.root)
            toolbar.update()
            canvas._tkcanvas.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)
    
            self.root.mainloop()
    

    In your code, you need to initialize the plotter like this:

    import pylab
    fig = matplotlib.pyplot.figure()
    Plotter(fig)
    

    Then you can plot to it like this:

    fig.gca().clear()
    fig.gca().plot([1,2,3],[4,5,6])
    fig.canvas.draw()
    

提交回复
热议问题