如何使用Matplotlib仅重绘更新的数据

时间:2015-03-25 11:02:05

标签: python matplotlib

如何重新绘制更新的数据,而不是从头开始清除整个图形和绘图?

(我不想要那样的https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/

到目前为止我的代码是这样的:(虽然,在这个例子中,我使用了一些我在Internet上找到的随机函数,而不是使用我正在使用的真实数据)

import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
#from matplotlib.figure import Figure
import matplotlib.animation as animation
from matplotlib import style
from matplotlib import pyplot as plt
from matplotlib.lines import Line2D

import numpy as np


f = plt.Figure()


class SubplotAnimation(animation.TimedAnimation):
    def __init__(self):

        fig= plt.figure()

        ax1 = fig.add_subplot(2, 1, 1)
        par = ax1.twinx()

        ax2 = fig.add_subplot(2, 1, 2)
        par2 = ax2.twinx()

        #********************** FUNCTIONS **************************************#
        dt = 1
        self.t = np.arange(0, 40, dt)
        self.nse1 = np.random.randn(len(self.t))                 # white noise 1
        self.nse2 = np.random.randn(len(self.t))                 # white noise 2
        self.nse3 = np.random.randn(len(self.t))                 # white noise 2
        self.r = np.exp(-self.t/0.05)

        cnse1 = np.convolve(self.nse1, self.r, mode='same')*dt   # colored noise 1
        cnse2 = np.convolve(self.nse2, self.r, mode='same')*dt   # colored noise 2
        cnse3 = np.convolve(self.nse3, self.r, mode='same')*dt   # colored noise 2

        # two signals with a coherent part and a random part
        self.x = 0.01*np.sin(2*np.pi*10*self.t) + cnse1
        self.y = 0.01*np.sin(2*np.pi*10*self.t) + cnse2
        self.k = 0.01*np.sin(2*np.pi*10*self.t) + cnse3
        self.z = 10 * self.t


        ax1.set_xlabel('x')
        ax1.set_ylabel('y')
        par.set_ylabel("y2")
        ###################### LINES ############################
        self.line1 = Line2D([], [], color='red', linewidth=2)
        self.line1a = Line2D([], [], color='black', linewidth=1)
        ax1.add_line(self.line1)
        par.add_line(self.line1a)
        ax1.set_xlim(0, 35)
        ax1.set_ylim(-10, 10)
        par.set_ylim(-10, 10)

        ax2.set_xlabel('x')
        ax2.set_ylabel('y')
        par2.set_ylabel("y2")
         ###################### LINES ############################
        self.line2 = Line2D([], [], color='black')
        self.line2a = Line2D([], [], color='red')
        self.line2b = Line2D([], [], color='grey')
        ax2.add_line(self.line2)
        par2.add_line(self.line2a)
        par2.add_line(self.line2b)
        ax2.set_xlim(0, 35)
        ax2.set_ylim(-0.5, 0.5)
        par2.set_ylim(-0.3, 0.3)

        animation.TimedAnimation.__init__(self, fig, interval=30, blit=True)

    def _draw_frame(self, framedata):
        i = framedata

        self.line1.set_data(self.t[:i], self.x[:i])
        self.line1a.set_data(self.t[:i], self.y[:i])

        self.line2.set_data(self.t[:i], self.x[:i])
        self.line2a.set_data(self.t[:i], self.y[:i])
        self.line2b.set_data(self.t[:i], self.k[:i])

        self._drawn_artists = [self.line1, self.line1a,
            self.line2, self.line2a, self.line2b]

    def new_frame_seq(self):
        return iter(range(self.t.size))

    def _init_draw(self):
        lines =  [self.line1, self.line1a,
            self.line2, self.line2a, self.line2b]
        for l in lines:
            l.set_data([], [])

ani = SubplotAnimation()
plt.show()

1 个答案:

答案 0 :(得分:0)

所以我有点解决了这个问题,但我也更改了代码......看看我的新代码,让我知道你是否有任何建议让它看起来更好: (您可能会在代码中找到未使用的内容,但因为我试图简化代码并删除一些代码等等)

import matplotlib
matplotlib.use("TkAgg") #the back-end of matplotlib
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
import Tkinter as tk

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.lines import Line2D
from matplotlib import style

ROTOR_SPEED = 100
PUMP_STATUS = False


LARGE_FONT = ("Verdana", 12)
NORM_FONT = ("Verdana", 10)
SMALL_FONT = ("Verdana", 8)

style.use("ggplot")


fig = plt.figure()
fig.set_size_inches(10, 7)
top_graph = plt.subplot2grid((2, 2), (0, 0), colspan=2)



line1 = Line2D([], [], color='black')

line2 = Line2D([], [], color='red', linewidth=2)

top_graph.add_line(line1)

top_graph.set_xlim(0, 24)
top_graph.set_ylim(-20, 20)

top_graph.set_aspect('equal', 'datalim')

line, = top_graph.plot([], [], lw=1)
line2, = top_graph.plot([], [], lw=3)
xdata, ydata = [], []
xline, yline = [], []


def data_gen():
    t = data_gen.t
    cnt = 0
    height = 15
    while cnt < 1000:


        yield t, np.sin(2 * np.pi * t / 10.), 2*[t]*(height), range(-height, height)
        cnt+=1
        t += 0.05
data_gen.t = 0

def run(data):
    # update the data
    t, y, t2, rang = data

    repeats = t//24

    run.index = int(round(t%24.0/0.05))

    if len(xdata) <= run.index:
        xdata.append(t)
        ydata.append(y)
        xline = t2
        yline = rang

    else:
        xdata[run.index] = t - (24 * repeats)
        ydata[run.index] = y

        xline = map(lambda (a, b): a-b, zip(t2, [24*repeats]*len(t2)))
        yline = rang



    line.set_data(xdata, ydata)
    line2.set_data(xline, yline)
    line2.set_color('white')
    return line, line2
run.index = 1




class MainPage(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        container = tk.Frame(self)

        container.pack(side="top", fill="both", expand = True)

        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)



        #********** FRAMES*******#

        self.frames = {} #empty..

        frame = GraphPage(container, self)

        self.frames[GraphPage] = frame

        frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(GraphPage)

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()



class GraphPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text="Example", font=LARGE_FONT)
        label.grid(row=0, column=0, sticky='N')

        canvas = FigureCanvasTkAgg(fig, self)

        canvas.show()
        canvas.get_tk_widget().grid(row=1, column=0, rowspan=6, columnspan=3, sticky='NSEW')

app = MainPage()
app.geometry("980x640")
ani = animation.FuncAnimation(fig, run, data_gen, blit=True, interval=20,
    repeat=False)
app.mainloop()