Python:更新图而不是创建一个新图

问题描述

我正在尝试使用Python编写Ising模型。

我认为,我已经正确编码了,但是动画或绘图有问题。我似乎为每种配置绘制了一个新映像,而不是更新现有配置,从而节省了大量我不需要的映像。如果可能的话,我只想更新一个图。

我知道,我正在循环内进行绘图,但是当我要绘制每次迭代时,我不记得这是一个问题。 Seaborn的热图可能有问题吗?

我已附上我的代码:

import numpy as np
import numpy.random as npr
import matplotlib.pyplot as plt
import seaborn as sns

#Constants
J = 1
h = 1
kbT = 1
beta = 1

#Grid
L = 20 #Dimensions
N = L**2 #Total number of grid points


#Initial configuration
spins = 2*np.random.randint(2,size = (L,L))-1


E = []
i = 0
plt.figure()

while i < 100000:
    for i in range(1,N):
        i += 1
        s = tuple(npr.randint(0,L,2)) # Random initial coordinate
    
        # x and y coordinate
        (sx,sy) = s
        # Periodic boundary condition
        sl = (sx-1,sy) 
        sr = ((sx+1)%L,sy)
        sb = (sx,sy-1)
        st = (sx,(sy+1)%L)
        # Energy
        E =   spins[s] * ( spins[sl] + spins[sr] + spins[sb] + spins[st] )
        if E <= 0 : # If negative,flip
            spins[s] *= -1
        else:
            x = np.exp(-E/kbT) # If positve,check condition
            q = npr.rand()
            if x > q: 
                spins[s] *= -1
    # Plot (heatmap)
    sns.heatmap(spins,cmap = 'magma')
    plt.pause(10e-10)
    plt.draw()
    plt.show()

解决方法

我认为函数ionclf可以解决问题。

import numpy as np
import numpy.random as npr
import matplotlib.pyplot as plt
import seaborn as sns

#Constants
J = 1
h = 1
kbT = 1
beta = 1

#Grid
L = 20 #Dimensions
N = L**2 #Total number of grid points

#Initial configuration
spins = 2*np.random.randint(2,size = (L,L))-1

E = []
i = 0

plt.ion()
plt.figure()
plt.show()

while i < 100000:
    for i in range(1,N):
        i += 1
        s = tuple(npr.randint(0,L,2)) # Random initial coordinate
    
        # x and y coordinate
        (sx,sy) = s
        # Periodic boundary condition
        sl = (sx-1,sy) 
        sr = ((sx+1)%L,sy)
        sb = (sx,sy-1)
        st = (sx,(sy+1)%L)
        # Energy
        E =   spins[s] * ( spins[sl] + spins[sr] + spins[sb] + spins[st] )
        if E <= 0 : # If negative,flip
            spins[s] *= -1
        else:
            x = np.exp(-E/kbT) # If positve,check condition
            q = npr.rand()
            if x > q: 
                spins[s] *= -1
    # Plot (heatmap)
    plt.clf()
    sns.heatmap(spins,cmap = 'magma')
    plt.pause(10e-10)

使用功能ion,您可以进行交互式绘图,因此您需要:

  • 使其具有互动性
  • 显示情节
  • 清除循环中的情节

Hereion函数的引用。

clf的引用是here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...