每当我绘制更多数据时,Matplotlib动画就会变慢

时间:2019-12-17 16:09:23

标签: python matplotlib

我正在实时绘制传感器数据。假设我将sensor_data存储在字典中。每当我绘制一组新的sensor_data时,它都会减慢绘制速度。

我知道有一种方法可以加快速度。我尝试了几种方法(即blit,保存和加载背景),但无法正确获取语法或方法。我希望有某种方法可以加快每秒的帧数,因为这会减慢一切。我想我已经用尽了现有的堆栈溢出。

import matplotlib.pyplot as plt

def plot_init():

    plt.ion() # interactive mode on
    fig, ax = plt.subplots(2, 2, figsize=(10, 10))
    plt.show(block=False)

    # set title according to axis
    ax[0, 0].set(title='Sensor 1')
    ax[0, 1].set(title='Sensor 2')
    ax[1, 0].set(title='Sensor 3')
    ax[1, 1].set(title='Sensor 4')

    # turn on grid for each subplot
    for a in fig.axes:
        a.grid()

    return fig, ax

def plot_sensor_data(fig, ax, sensor_data):

    plot1, = ax[0, 0].plot(sensor_data["some_sensor"], 'C0')
    plot2, = ax[0, 0].plot(sensor_data["some_other_sensor"], 'C1')
    ax[0, 0].legend([plot1, plot2], ['some_sensor', 'some_other_sensor'])

    # ...

    axes[1, 1].plot(sensor_data["another_sensor"], 'C0')

    plt.draw()
    plt.pause(0.01)

if __name__ == "__main__":

    sensor_data = {}
    fig, ax = plot_init()

    while True:

        sensor_data = get_sensor_data() 
        plot_sensor_data(fig, ax, sensor_data)

1 个答案:

答案 0 :(得分:0)

我能够找到一个对我有用的解决方案。

class SensorPlot():

    def __init__(self):

        plt.show()

        self.sample = 0

        self.xdata = []
        self.ydata = []

        self.xdata2 = []
        self.ydata2 = []

        self.xdata3 = []
        self.ydata3 = []

        fig, self.axes = plt.subplots(2, 2, figsize=(10,10))

        for a in fig.axes:
            a.grid()

        self.line1, = self.axes[0,0].plot(self.ydata)
        self.line2, = self.axes[0,0].plot(self.ydata2)
        self.axes[0, 0].legend([self.line1, self.line2], ['some_sensor', 'some_other_sensor'])

        self.line3, = self.axes[0, 1].plot(self.ydata3)
        self.axes[0, 1].legend([self.line3, self.line4], ['another_sensor'])

        # ...

    def plot_data(self, my_bud):

        self.xdata.append(self.sample)

        self.ydata.append(sensor_data["some_sensor"][-1])
        self.line1.set_xdata(self.xdata)
        self.line1.set_ydata(self.ydata)

        self.ydata2.append(sensor_data["some_other_sensor"][-1])
        self.line2.set_xdata(self.xdata)
        self.line2.set_ydata(self.ydata2)

        self.ydata3.append(sensor_data["another_sensor"][-1])
        self.line3.set_xdata(self.xdata)
        self.line3.set_ydata(self.ydata3)

        self.sample = self.sample + 1

        self.axes[0,0].relim()
        self.axes[0,0].autoscale_view(True, True, True)

        self.axes[1,0].relim()
        self.axes[1,0].autoscale_view(True, True, True)

        plt.draw()
        plt.pause(1e-17)