首页 > 解决方案 > Python Matplotlib 实时数据绘图问题

问题描述

我试图编写一个类,它会接收一些值,然后它会绘制进去。图形将是连续的线。然而,问题是图形值总是由于某种原因总是落后 1 个条目。

from matplotlib import pyplot as plt

class RealTimeGraph():
    x = []
    y = []

    def __init__(self, y_range = (), x_range = ()):
        self.index = self.index_gen()

        if (y_range):
            plt.ylim(*y_range)
        if (x_range):
            plt.xlim(*x_range)

    def index_gen(self, start = 0):
        while True:
            yield start
            start += 1

    def add_value(self, value):
        self.x.append(next(self.index))
        self.y.append(value)

        plt.cla()
        plt.plot(self.x, self.y)
        plt.pause(0.005)


if __name__ == '__main__':
    import random as r
    import time

    graph = RealTimeGraph(y_range = (0, 5))

    for i in range(10):
        graph.add_value(r.randint(0, 5))
        time.sleep(0.5)

睡眠功能是模拟程序,我想在其中使用这个类。是什么导致了这个问题?

标签: pythonmatplotlibreal-time

解决方案


推荐阅读