【问题标题】:Updating a matrix plot in matplotlib during for cycle在 for 循环期间更新 matplotlib 中的矩阵图
【发布时间】: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


【解决方案1】:

问题是每次调用 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 2,知道为什么吗?
  • 它适用于我在 python 2.7.11 和 3.4.2 中(有点过时)您希望使用哪个版本?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-19
相关资源
最近更新 更多