创建一个动画热图,并在课堂上进行热图变化

2024-06-16 11:08:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我在模拟伊辛模型时遇到了一个问题(不重要)。你知道吗

我的问题是二进制热图的动画,其中我的数组由一个函数调制:

似乎我的heatdata函数在动画中只被调用了一次:

'''IsingArray Class'''
import numpy as np
import random as rd
import functions as fun
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.animation as animation

class IA:   
  def __init__(self,long):
      self.dim=long

      '''Array'''
      self.IsingArray=np.ndarray((self.dim,self.dim))


      '''Inititate Sites'''
      for i in range(self.dim):
          for j in range(self.dim):
              if rd.random()>=0.5:
                  self.IsingArray[i,j]=1
              else:
                  self.IsingArray[i,j]=-1
      self.raspl=0           
      self.fig = plt.figure()

  def heatdata(self,i):
          plt.clf()
          FP=sns.heatmap(self.IsingArray, linewidth=0.5,vmin=-1,vmax=1,cmap='bwr')
          colorbar=FP.collections[0].colorbar
          colorbar.set_ticks([-1,1])
          colorbar.set_ticklabels(['DOWN','UP'])`
          #replace 
          self.IsingArray[rd.randint(0,self.dim-1),rd.randint(0,self.dim-1)]=1
          self.raspl+=1


  def animate(self,nof,safe=False):
       animateMe = animation.FuncAnimation(self.fig, self.heatdata(self), nof,interval=100,repeat=False )
       if safe==True:
           animateMe.save('FieldChange'+'.mp4', fps=20, extra_args=['-vcodec', 'libx264'])
       plt.show()

#---------actual programm-----------#

long=5

Ising=IA(long)

print(Ising.raspl)
Ising.animate(10)
print(Ising.raspl)

Tags: importselfdefas动画pltrdlong