【问题标题】:Python animation from file来自文件的 Python 动画
【发布时间】:2020-12-03 05:45:08
【问题描述】:

我正在尝试为某些功能设置动画。我的 x 值是恒定的(范围在整个动画中不会改变):

x = np.linspace(0,1,N)

我将我的 y 值作为帧存储在文件中,并用新行分隔:

1 
2
3

1.2
1.9
2.8

如何一次显示帧中的所有值,然后移动到另一个帧?

【问题讨论】:

  • 你能详细描述一下你打算做什么吗?

标签: python matplotlib animation plot


【解决方案1】:

我首先使用您指定的格式在名为 data.txt 的文件中创建模拟数据:

import numpy as np

def your_func(x, a):
    return np.sin(x + a)

n_cycles = 4
n_frames = 100

xmin = 0
xmax = n_cycles*2*np.pi
N = 120

x = np.linspace(xmin, xmax, N)

with open('data.txt', 'w') as fout:
    for i in range(n_frames):
        alpha = 2*np.pi*i/n_frames
        y = your_func(x, alpha)
        for value in y:
            print(f'{value:.3f}', file=fout)
        print(file=fout)

数据文件如下所示:

0.000  # First frame
0.210
...
-0.210
-0.000

0.063  # Second frame
0.271
...
-0.148
0.063

...

-0.063  # Frame 100
0.148
...
-0.271
-0.063

然后我从磁盘读取这些数据:

def read_data(filename):
    with open(filename, 'r') as fin:
        text = fin.read()
    values = [[]]
    for line in text.split('\n'):
        if line:
            values[-1].append(float(line))
        else:
            values.append([])
    return np.array(values[:-2])

y = read_data('data.txt')

动画生成如下:

from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation

def plot_background():
    line.set_data([], [])
    return line,

def animate(i):
    line.set_data(x, y[i])
    return line,

fig = plt.figure()
ax = plt.axes(xlim=(x[0], x[-1]), ylim=(-1.1, 1.1))
line, = ax.plot([], [], lw=2)

anim = FuncAnimation(fig, animate, init_func=plot_background,
                     frames=n_frames, interval=10, blit=True)

anim.save(r'animated_function.mp4', 
          fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()

更详细的解释请看this blog

【讨论】:

    【解决方案2】:

    根据我对您所问内容的理解,这个问题已经得到解答。链接是https://stackoverflow.com/a/33275455/8513445

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation
    
    x = np.linspace(0,1,6)
    y = [1,2,3,1.2,1.9,2.8]
    
    fig = plt.figure()
    plt.xlim(0, 4)
    plt.ylim(0, 4)
    graph, = plt.plot([], [], 'o')
    
    def animate(i):
        graph.set_data(x[:i+1], y[:i+1])
        return graph
    
    ani = FuncAnimation(fig, animate, frames=12, interval=200)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-02
      • 2014-04-16
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      • 2019-10-09
      • 2012-11-01
      • 2014-10-14
      相关资源
      最近更新 更多