我正在運行仿真,我需要更新每次迭代(或每n次迭代)的矩陣圖。我正在使用matplotlib繪圖,特別是matshow。我嘗試複製我在其他StackOverflow問題中看到的代碼,但是我沒有成功。目前代碼只是用新圖形生成不同的窗口,而不是更新第一個窗口。以下是目前爲止的代碼:在循環中更新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 = 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)
謝謝!
我強烈建議你n_iter更改爲更合理的這段代碼,運行此其他不知情的人會得到打開10,000個新的窗口。 – zephyr
糟糕,你完全正確。現在改變它。 – user3930598
不直接解決您的問題,但您可以嘗試其他不需要使用matshow的繪圖方法。 'imshow'可能接近你要找的東西。 – zephyr