Matplotlib 在我的图表上显示旧数据与新数据混合,但 Line2D.get_data() 显示旧数据已删除。为什么图表仍然显示旧数据?

Matplotlib is shows old data mixed with new data on my chart, but Line2D.get_data() shows old data is deleted. Why does chart still show old data too?

我有一个 class 可以通过内置的 PubSub 样式功能处理绘制新数据。当发布者设置新值时,它会调用 update:

def update(self, index, value):
    if index > len(self.values) - 1:
        print("Index exceeds length of chart values")
        raise
    else:
        self.values[index] = value
    # self.line is matplotlib.lines.Line2D, and self.fig is the figure, both created in __init__
    self.line.set_xdata(self.values)
    self.line.set_ydata([0 for v in self.values]) # I just want to see the x-dispersion of points
    self.fig.canvas.draw_idle()
    print(str(self.line.get_data()))

当我尝试时:

chart.update(2, 3.14159)
chart.update(2, 2.71828)

我看到我的数据已经更新了;索引 2 处的旧数据已被覆盖。然而,当图形重绘时,新点显示出来,但旧点也没有被替换!我做错了什么?

我无法重现您的行为。总是有相同数量的可见点,更新只影响相应索引处的值。

import matplotlib.pyplot as plt

class Test:
    def __init__(self):
        self.fig, ax = plt.subplots()
        self.values = [1, 2, 9]
        self.line = ax.plot(self.values, [0 for v in self.values], 
                            ls='', color='k', marker='o')[0]

    def update(self, index, value):
        if index > len(self.values) - 1:
            print("Index exceeds length of chart values")
            raise
        else:
            self.values[index] = value
        self.line.set_xdata(self.values)
        self.fig.canvas.draw_idle()
        print(str(self.line.get_data()))


test = Test()
test.update(index=1, value=5)
test.update(index=1, value=2)