Skip to main content
 首页 » 编程设计

python之在循环期间更新 matplotlib 中的矩阵图

2024年10月24日10mayingbao

我正在运行模拟,我需要在每次迭代(或每 n 次迭代)中更新矩阵图。我正在使用 matplotlib 进行绘图,特别是 matshow。我尝试复制我在其他 StackOverflow 问题中看到的代码,但没有成功。目前,代码只是用新图生成不同的窗口,而不是更新第一个。到目前为止,这是代码:

import numpy as np 
import random 
import math 
import matplotlib.pyplot as plt 
import matplotlib.animation as anim 
 
#   System variables initialization 
N = 50 
n_iter = 5 
betaJ = 0.40 
lattice = np.ones([N, N]) 
energy = -2*betaJ*N**2 
choices = list(range(N)) 
 
plt.ion() 
fig = plt.figure() 
 
#   Main cycle 
for i in range(0, n_iter): 
    #   Pick random spin and calculate energy variation caused by flipping it 
    x, y = random.choice(choices), random.choice(choices) 
    neighbour_spin_sum = lattice[np.mod(x-1, N), y] + lattice[np.mod(x+1, N), y] + lattice[x, np.mod(y+1, N)] + lattice[x, np.mod(y-1, N)] 
    delta_energy = 2*betaJ*(neighbour_spin_sum*lattice[x, y]) 
 
    #   If energetically favorable, flip spin 
    if delta_energy < 0: 
        lattice[x, y] = -lattice[x, y]  
 
    #   Else flip with some probability 
    elif random.uniform(0, 1) <= math.exp(-delta_energy): 
        lattice[x, y] = -lattice[x, y]  
 
    plt.matshow(lattice) 
    plt.draw() 
    plt.pause(0.0001) 

谢谢!

请您参考如下方法:

问题是每次调用 plt.matshow() 时,matplotlib 都会创建一个新的绘图轴。为了解决这个问题,定义轴并继续重复使用它,如下所示:

import numpy as np 
import random 
import math 
import matplotlib.pyplot as plt 
import matplotlib.animation as anim 
 
#   System variables initialization 
N = 50 
n_iter = 10000 
betaJ = 0.40 
lattice = np.ones([N, N]) 
energy = -2 * betaJ * N ** 2 
choices = list(range(N)) 
 
plt.ion() 
fig = plt.figure() 
 
#   Main cycle 
for i in range(0, n_iter): 
    #   Pick random spin and calculate energy variation caused by flipping it 
    x = random.choice(choices) 
    y = random.choice(choices) 
    neighbour_spin_sum = lattice[np.mod(x-1, N), y] + lattice[np.mod(x+1, N), y] + lattice[x, np.mod(y+1, N)] + lattice[x, np.mod(y-1, N)] 
 
    delta_energy = 2*betaJ*(neighbour_spin_sum*lattice[x, y]) 
 
    #   If energetically favorable, flip spin 
    if delta_energy < 0: 
        lattice[x, y] = -lattice[x, y]  
 
    #   Else flip with some probability 
    elif random.uniform(0, 1) <= math.exp(-delta_energy): 
        lattice[x, y] = -lattice[x, y]  
 
    ax = fig.add_subplot(111) 
    ax.matshow(lattice) 
    plt.draw() 
    plt.pause(0.0001)