python - 在三重 for 循环中从 plt.imshow 创建 matplotlib 动画

标签 python animation matplotlib jquery-animate imshow

我在显示的代码中使用 matplotlib.animation 时遇到了一些问题:

# creates grid of 1's/-1's of dimensions specified.
arr1 = np.random.choice([1.,-1.],[xarray,yarray])

# arr will be the 2-d array iterated.
arr = arr1

# time, row and column loops.
for t in range(0,time1):
    for i in range(0,x):
        for j in range(0,y):

            Echange=energy_change(arr,i,j) # change in energy for this flip.
            P_flip = np.exp(-Echange / kT) # probability of this flip occurring.

            if random.random() < P_flip: # condition to accept flip. 
                arr[i][j]=-1*arr[i][j]

    image = plt.imshow(arr) # plots image of Ising model after (time) iterations.

    if t==0:
        plt.show()
    else:
        plt.draw()

为了清楚起见,我已经删除了我的动画尝试。基本上我想制作一个在指定时间后停止的窗口动画,没有任何计算延迟(运行此代码显示动画,但运行不一致或不流畅)。有没有办法计算所有迭代,然后显示动画窗口?我将感谢您的任何贡献!

最佳答案

当然,将计算与动画分开是完全可能的。 一种选择是创建一个大数组,其中前两个维度保存网格,最后一个维度保存时间步长。然后可以先填充数组,然后将其绘制在动画中。

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

N = 10
T = 100
a = np.zeros((N,N,T))
# creates grid of 1's/-1's of dimensions specified.
a[:,:,0] = np.random.choice([1.,-1.],(N,N) )

# time, row and column loops.
for t in range(1,T):
    a[:,:,t] = a[:,:,t-1]
    for i in range(0,N):
        for j in range(0,N):
            P_flip = 0.3
            if np.random.random() < P_flip: # condition to accept flip. 
                 a[i,j,t]=-1*a[i,j,t]


#### Plotting #####
fig = plt.figure()
im = plt.imshow(a[:,:,0], interpolation="none", cmap="Blues")
title = plt.title("")

def update(t):
    im.set_array(a[:,:,t])
    title.set_text(str(t))

ani = matplotlib.animation.FuncAnimation(fig, func=update, frames=T, 
                       repeat=False, interval=100)
plt.show()

关于python - 在三重 for 循环中从 plt.imshow 创建 matplotlib 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41379704/

相关文章:

python - Shell 脚本在其间更改 shell

python - 如果以上都不是python

iphone - 以编程方式使用要设置动画的图像填充数组

python - 根据参数绘制具有不同颜色的曲线

python - 无法使用plt.imshow显示图片

python - 如何从Python字典列表中提取重复的键和值?

python - 当 Django `User` 的主键是 `CharField` 时登录时出错

jQuery 动画在 Chrome 动画之前跳转

java - 图像上的简单动画存在问题

Matplotlib 散点图图例 : Customize handles to look like tiny scatter plots