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

时间:2016-03-03 19:44:32

标签: python matplotlib plot

我正在运行模拟,我需要在每次迭代时更新矩阵图(或者每次迭代都更新一次)。我正在使用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)

谢谢!

1 个答案:

答案 0 :(得分:2)

问题在于,每次调用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)