2017-08-10 73 views
0

我想顯示兩個圖,它們不斷由我的程序更新。但是,我的嘗試解決方案只能顯示兩個圖形中的第二個,而第一個圖形只顯示爲空白窗口。繪製多個永久圖

這裏是我的代碼:

def show1(x, y): 
    fig = plt.figure(1) 
    fig.canvas.set_window_title("Plot1") 
    plt.plot(x, y) 
    plt.pause(0.01) 
    plt.show() 
    plt.figure(1).clear() 

def show2(x, y): 
    fig = plt.figure(2) 
    fig.canvas.set_window_title("Plot2") 
    plt.plot(x, y) 
    plt.pause(0.01) 
    plt.show() 
    plt.figure(2).clear() 

plt.ion() 
x = [1, 2, 3, 4] 
i = 0 

while True: 
    y1 = [j + i for j in x] 
    show1(x, y1) 
    y2 = [j + 2 * i for j in x] 
    show2(x, y2) 
    time.sleep(2) 
    i += 1 

所以在循環的每個迭代,要繪製的值被更新,並且圖表被重新繪製。繪製完每幅圖後,我打電話給plt.figure(k).clear()以清除圖k,這樣下次我寫入圖時,我會在空白畫布上寫下(而不是將多個圖連續添加到同一圖中)。

但是會發生什麼,暫時我看到第一個圖顯示它的圖,但是當第二個圖被繪製時,第一個圖成爲一個空白窗,並且只有第二個圖實際上保持其顯示情節。

我該如何修改我的代碼,以便兩個圖形都具有持久顯示?

+0

如果清除了圖plt.figure(1).clear(),那麼該數字將是空白的。這裏毫不奇怪。關於動畫matplotlib周圍的情節有很多問題。你爲什麼不使用這些或者至少告訴他們有多遠他們不幫你? – ImportanceOfBeingErnest

+0

我認爲這不一定是正確的,因爲'plt.figure(2).clear()'不能清除圖2.圖2顯示了它的圖,而圖1則沒有。 – Karnivaurus

+0

圖2顯示了2秒的情節,而圖1顯示了它的0.01。因此你認爲它沒有被顯示。我已經厭倦瞭解釋如何每週動畫一次或兩次,也許別人會提供一個答案,否則只是谷歌的工作解決方案。 – ImportanceOfBeingErnest

回答

1

我希望這是你想要的。

import matplotlib.pyplot as plt 
import time 

fig1, ax1 = plt.subplots() 
fig1.canvas.set_window_title("Plot1") 

fig2, ax2 = plt.subplots() 
fig2.canvas.set_window_title("Plot2") 

x = [1, 2, 3, 4] 
i = 0 
# initial plots, so Lines objects exist 
line1, = ax1.plot(x, [j + i for j in x]) 
line2, = ax2.plot(x, [j + 2 * i for j in x]) 

def show1(y): 
    line1.set_ydata(y) # update data, i.e. update Lines object 
    ax1.relim() # rescale limits of axes 
    ax1.autoscale_view() # rescale limits of axes 
    fig1.canvas.draw() # update figure because Lines object has changed 

def show2(y): 
    line2.set_ydata(y) 
    ax2.relim() 
    ax2.autoscale_view() 
    fig2.canvas.draw() 

while True: 
    y1 = [j + i for j in x] 
    show1(y1) 
    y2 = [j + 2 * i for j in x] 
    show2(y2) 
    time.sleep(2) 
    i += 1 

而是一遍又一遍清的身影,剛剛更新的情節(即Lines對象)。這可能很有用,例如當包含Slider時(參見here,部分代碼來自matplotlib示例)。