【问题标题】:How to draw (animate) random process from the start (python)?如何从一开始就绘制(动画)随机过程(python)?
【发布时间】:2019-04-22 11:02:50
【问题描述】:

我想从一步一步更新的开始 (0,0) 中绘制随机过程路径。我使用了 matplotlib 动画,但它画了一条简单的线。如何绘制路径?

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

# Process simulation (Wiener process)
n = 1000
sd = np.sqrt(0.1)
w = np.zeros(n)
for i in range(n-1):
    w[i+1] = w[i] + np.random.normal(0, sd)


# Set up the figure, the axis, and the plot element to animate
fig = plt.figure()
ax = fig.add_subplot(111)    
ax.set_xlim([0, 1000])
ax.set_ylim([-50, 50])
th = np.linspace(0., n, n / 0.1, endpoint=False)
line, = ax.plot([],[],'b-', animated=True)
line.set_xdata(th)



# Animation function
def update(data):    
    line.set_ydata(data)
    return line,

def data_gen():
    t = -1
    while True:
        t +=1
        yield w[t]


# Call the animation
anim = animation.FuncAnimation(fig, update, data_gen, interval=10, blit=True)
plt.show()

【问题讨论】:

    标签: python-3.x matplotlib animation


    【解决方案1】:
    1. 在单独的脚本中生成数据。
    2. 将此数据保存到不断更新的 .csv 文件中(我更喜欢使用 pandas)
    3. 在其自己的控制台中运行图表,但将其设置为根据 csv 数据进行更新(我会使用 pandas)

    【讨论】:

    • 有没有办法以某种方式修改现有代码?因为这只是一个大程序的一部分,额外的脚本、数据文件等很不方便..
    • 我以前做过一个类似的项目,但我找不到,所以我现在只是想再次写出代码。
    • 我的意思是,更改函数“动画”或在现有代码中使用另一个函数,而不是制作 .csv 文件和两个附加脚本。
    • 如果您的数据是在 while 循环中生成的,控制台将继续读取该 while 循环,并且它不会执行您的其余代码,直到不再满足执行该 while 循环的条件.
    【解决方案2】:

    此代码使用我编写的名为celluloid 的库。在引擎盖下,它使用 ArtistAnimation 而不是 FuncAnimation,这实际上意味着它的内存效率不是很高。这段代码运行了大约一分钟。在我看来,代码更容易阅读,但我肯定有偏见。

    import numpy as np
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    from celluloid import Camera
    
    n = 1000
    w = np.cumsum(np.sqrt(0.1) * np.random.randn(n))
    fig = plt.figure()
    camera = Camera(fig)
    for i in range(n):
        plt.plot(w[:i], color='blue')
        camera.snap()
    anim = camera.animate(interval=10, blit=True)
    anim.save('weiner.mp4')
    

    【讨论】:

    • 哇!谢谢你!虽然一分钟相当长.. 有没有办法在某个时候停止动画,例如按下回车按钮?
    • 不幸的是,我不知道有什么容易的。这当然是可能的,但您可能需要使用 Jupyter 或一些 javascriptpython 之类的东西,例如 Bowtie 或 Dash。可能有一个内置的 matplotlib 解决方案,但如果是这样,我从未使用过它。您可能想为此提出一个新问题。
    猜你喜欢
    • 2013-10-25
    • 2016-01-13
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 2021-02-07
    相关资源
    最近更新 更多