2016-03-03 43 views
2

我正在運行仿真,我需要更新每次迭代(或每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) 

謝謝!

+0

我強烈建議你n_iter更改爲更合理的這段代碼,運行此其他不知情的人會得到打開10,000個新的窗口。 – zephyr

+0

糟糕,你完全正確。現在改變它。 – user3930598

+0

不直接解決您的問題,但您可以嘗試其他不需要使用matshow的繪圖方法。 'imshow'可能接近你要找的東西。 – zephyr

回答

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) 
+0

感謝您的回覆!這似乎只適用於Python 2,任何想法爲什麼? – user3930598

+0

它適用於我在Python 2.7.11和3.4.2(這是有點過時)哪個版本具體是你期待與它一起使用? – veda905