我正在为以下代码制作动画。我基本上想绘制一个值为-1或1的NxM矩阵,并通过函数运行该矩阵以随时间改变图像。有人可以告诉我哪里出了问题吗?我以这个网站为例https://matplotlib.org/examples/animation/dynamic_image.html。这是我正在使用的代码:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# white is + black is -
# NxM array of spins
def random_spin_field(N,M):
return np.random.choice([-1,1], size=(N,M))
def display_spin_field(field):
return plt.imshow(random_spin_field(1000, 1000),interpolation='nearest',cmap = 'binary')
## Ising Model
# Interaction (ferromagnetic if positive, antiferromagnetic if negative, non-ferromagnetic if zero)
Interaction = 0
# every point in the grid
def ising_step(field, beta=2): #beta is T**-1
N, M = field.shape
for n_offset in range(2): # change order to do the pixels, ie skip pixels
for m_offset in range(2):
for n in range(n_offset, N, 2):
for m in range(m_offset, M, 2):
_ising_update(field, n, m, beta) #calculate energy
images = field
return im,
def _ising_update(field, n, m, beta):
total = 0 #sum of all of the spins +/-1 of the neighboring points
N, M = field.shape
for i in range(n-1, n+2):#####loops between the
for j in range(m-1, m+2):# block of 9 points including the point itself
if i == n and j == m: #remove the point itself
continue
total += field[i % N, j % M] *Interaction
dE = 2 * field[n, m] * total #compute the energy
if dE <= 0: #if energy is improved by switching
field[n, m] *= -1 #switch
elif np.exp(-dE * beta) > np.random.rand(): # prob. of switching anyway
field[n, m] *= -1
images = [random_spin_field(100, 100)]
fig = plt.figure()
im = plt.imshow(images,interpolation='nearest',cmap = 'binary', animated=True)
ani = FuncAnimation(fig, ising_step(images[-1]), blit=True)
plt.show()
这是我得到的错误:
Traceback (most recent call last):
File "C:\...\Termo3.py", line 46, in <module>
im = plt.imshow(images,interpolation='nearest',cmap = 'binary', animated=True)
File "C:\Users\...\Programs\Python\Python36-32\lib\site-packages\matplotlib\pyplot.py", line 3101, in imshow
**kwargs)
File "C:\...\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\__init__.py", line 1717, in inner
return func(ax, *args, **kwargs)
File "C:\...\Programs\Python\Python36-32\lib\site-packages\matplotlib\axes\_axes.py", line 5127, in imshow
im.set_data(X)
File "C:\...\Programs\Python\Python36-32\lib\site-packages\matplotlib\image.py", line 611, in set_data
raise TypeError("Invalid dimensions for image data")
TypeError: Invalid dimensions for image data