本文介绍了动画“成长"Python/Matplotlib 中的线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我想生成一组可用于为不断增长的线图制作动画的帧.过去,我一直使用 plt.draw() 和 set_ydata() 来重绘 y 数据,因为它会随着时间的推移而变化.这一次,我想画一条增长"线,随着时间在图形上移动.因此, set_ydata 不起作用(xdata 正在改变长度).例如,

I want to produce a set of frames that can be used to animate a plot of a growing line. In the past, I have always used plt.draw() and set_ydata() to redraw the y-data as it changed over time. This time, I wish to draw a "growing" line, moving across the graph with time. Because of this, set_ydata doesn't work (xdata is changing length). For example,

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure()
for n in range(len(x)):
    plt.plot(x[:n], y[:n], color='k')
    plt.axis([0, 10, 0, 1])
    plt.savefig('Frame%03d.png' %n)

虽然这有效,但随着它的扩展,它变得非常缓慢.有没有更快的方法来做到这一点?

While this works, it becomes very slow as it scales. Is there a faster way to do this?

推荐答案

注意事项:

首先,事情变得越来越慢的原因是您在同一位置绘制了越来越多的重叠线.

First off, the reason that things become progressively slower is that you're drawing more and more and more overlapping lines in the same position.

一个快速的解决方法是每次都清除绘图:

A quick fix is to clear the plot each time:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure()
for n in range(len(x)):
    plt.cla()
    plt.plot(x[:n], y[:n], color='k')
    plt.axis([0, 10, 0, 1])
    plt.savefig('Frame%03d.png' %n)

不过,最好同时更新 x 和 y 数据:

Better yet, however, update both the x and y data at the same time:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)
y = np.sin(x)

fig, ax = plt.subplots()
line, = ax.plot(x, y, color='k')

for n in range(len(x)):
    line.set_data(x[:n], y[:n])
    ax.axis([0, 10, 0, 1])
    fig.canvas.draw()
    fig.savefig('Frame%03d.png' %n)

如果您想使用动画模块(旁注:blit=True 在某些后端(例如 OSX)上可能无法正常工作,请尝试 blit=False代码>如果您有问题):

And if you'd like to use the animation module (side note: blit=True may not work properly on some backends (e.g. OSX), so try blit=False if you have issues):

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

x = np.linspace(0, 10, 100)
y = np.sin(x)

fig, ax = plt.subplots()
line, = ax.plot(x, y, color='k')

def update(num, x, y, line):
    line.set_data(x[:num], y[:num])
    line.axes.axis([0, 10, 0, 1])
    return line,

ani = animation.FuncAnimation(fig, update, len(x), fargs=[x, y, line],
                              interval=25, blit=True)
ani.save('test.gif')
plt.show()

这篇关于动画“成长"Python/Matplotlib 中的线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 14:01