【问题标题】:Matplotlib how to move axis along data in a real-time animationMatplotlib如何在实时动画中沿数据移动轴
【发布时间】:2021-09-16 11:51:57
【问题描述】:

我正在尝试绘制在运行时生成的数据。为此,我使用matplotlib.animation.FuncAnimation

虽然数据显示正确,但轴值并未根据正在显示的值进行相应更新:

x 轴显示从 0 到 10 的值,尽管我在 update_line 函数的每次迭代中更新它们(参见下面的代码)。

DataSource 包含数据向量并在运行时附加值,并返回正在返回的值的索引:

import numpy as np

class DataSource:
    data = []
    display = 10

    # Append one random number and return last 10 values
    def getData(self):
        self.data.append(np.random.rand(1)[0])
        if(len(self.data) <= self.display):
            return self.data
        else:
            return self.data[-self.display:]

    # Return the index of the last 10 values
    def getIndexVector(self):
        if(len(self.data) <= self.display):
            return list(range(len(self.data)))

        else:
            return list(range(len(self.data)))[-self.display:]

我从 matplotlib 文档中获得了 plot_animation 函数。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from datasource import DataSource


def update_line(num, source, line):
    data = source.getData()
    indexs = source.getIndexVector()
    if indexs[0] != 0:
        plt.xlim(indexs[0], indexs[-1])
        dim=np.arange(indexs[0],indexs[-1],1)
        plt.xticks(dim)
    line.set_data(indexs,data)
    return line,

def plot_animation():
    fig1 = plt.figure()
    source = DataSource()

    l, = plt.plot([], [], 'r-')

    plt.xlim(0, 10)
    plt.ylim(0, 1)
    plt.xlabel('x')
    plt.title('test')
    line_ani = animation.FuncAnimation(fig1, update_line, fargs=(source, l),
                                    interval=150, blit=True)

    # To save the animation, use the command: line_ani.save('lines.mp4')


    plt.show()

if __name__ == "__main__":
    plot_animation()

如何在动画的每次迭代中更新 x 轴值?

(如果您发现任何错误,我感谢您提出改进代码的建议,即使它们可能与问题无关)。

【问题讨论】:

  • 动画函数中graph的数据集在IF函数外是不是正确,我是这么认为的,因为我在IF函数中设置了plt.xlim(indexes,data)
  • 图表显示 10 个值。 IF 语句确保(或至少我希望它确保)轴仅在集合中有超过 10 个值时才更新,因此它必须“移动”到右侧。
  • 我实际上让代码工作了。由于我们绘制的数据小于 1.0,我认为我们可以通过在图表的数据集之后添加以下内容来处理它。 line.set_data(indexs,data);plt.xlim(indexs[0], indexs[-1])
  • 我们将在第一次迭代时将 xlim 设置为 (1,1),因为数据集中只有一个元素。这个答案不正确。

标签: python matplotlib matplotlib-animation


【解决方案1】:

这里有一个简单的例子来说明如何实现这一点。

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
%matplotlib notebook

#data generator
data = np.random.random((100,))

#setup figure
fig = plt.figure(figsize=(5,4))
ax = fig.add_subplot(1,1,1)

#rolling window size
repeat_length = 25

ax.set_xlim([0,repeat_length])
ax.set_ylim([-2,2])


#set figure to be modified
im, = ax.plot([], [])

def func(n):
    im.set_xdata(np.arange(n))
    im.set_ydata(data[0:n])
    if n>repeat_length:
        lim = ax.set_xlim(n-repeat_length, n)
    else:
        lim = ax.set_xlim(0,repeat_length)
    return im

ani = animation.FuncAnimation(fig, func, frames=data.shape[0], interval=30, blit=False)

plt.show()

#ani.save('animation.gif',writer='pillow', fps=30)

【讨论】:

  • 感谢您的回答,我的问题是FuncAnimation 行中的blit 选项,轴没有移动,因为我将其设置为True。我的其余代码都很好。
  • 酷,很高兴能帮上忙。很高兴看到您弄清楚所需的代码修改!如您所见,我还在回答中展示了blit=False,以及滚动窗口修改。
  • 是的,多亏了你的回答,我确实注意到了这一点,赞成帮助:)
【解决方案2】:

解决方案

我的问题出在下面一行:

line_ani = animation.FuncAnimation(fig1, update_line, fargs=(source, l),
                                    interval=150, blit=True)

我要做的是将blit 参数更改为False,x 轴开始按需要移动。

【讨论】:

    猜你喜欢
    • 2020-11-09
    • 2021-02-11
    • 1970-01-01
    • 2017-03-25
    • 2021-07-24
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多