【发布时间】:2016-03-03 19:44:32
【问题描述】:
我正在运行一个模拟,我需要在每次迭代(或每 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)
谢谢!
【问题讨论】:
-
我强烈建议您将 n_iter 更改为更合理的代码,否则运行此代码的毫无戒心的人会打开 10,000 个新窗口。
-
糟糕,你完全正确。立即更改。
-
不能直接解决您的问题,但您可以尝试其他不需要使用 matshow 的绘图方法。
imshow可能与您要查找的内容很接近。
标签: python matplotlib plot