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

标签 python matplotlib plot

我正在运行模拟,并且需要在每次迭代(或每 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)

关于python - 在 for 循环期间更新 matplotlib 中的矩阵图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35781577/

相关文章:

python - `antialiased`中的 `matplotlib.collections`是什么,怎么给它设置参数?

r - 在不影响情节的情况下控制ggplot2图异常(exception)观

javascript - 用 pako(javascript 中的 zlib)压缩,用 zlib(python)解压不起作用

python - 一个返回字典值的python函数

python - 使用 matplotlib 绘图时出现错误

python - 如何删除/隐藏 matplotlib slider 值

Python MatplotLib 绘制 x 轴,第一个 x 轴值标记为 1(而不是 0)

python - Pandas 数据框到具有 bool 系列的结构化数组

python - Django celery : create periodic task at runtime with schedule depending on user input

python - Plotly:如何向烛台图表添加交易量