2017-08-29 32 views
0

我想每隔x秒更新一次繪圖並保持共享的x軸。問題是,使用CLA時()命令sharedx丟失和不使用CLA()時,不更新的情節,但「overplotted」,因爲在這個小例子:Python Matplotlib:在循環中更新圖形時保持共享x軸

import matplotlib.pyplot as plt 
import pandas as pd 

data = pd.DataFrame([[1,2,1],[3,1,3]], index = [1,2]) 

n_plots = data.shape[1] 

fig, axs = plt.subplots(n_plots , 1, sharex = True) 
axs = axs.ravel() 

while True: 
    for i in range(n_plots): 
     #axs[i].cla() 
     axs[i].plot(data.iloc[:,i]) 
     axs[i].grid() 

    plt.tight_layout() 
    plt.draw() 

    plt.pause(5) 

    data = pd.concat([data,data]).reset_index(drop = True) 

行爲可以通過取消axs [i] .cla()行的註釋來看到。

所以問題是: 如何在while循環(我想更新一些數據)中更新一個繪圖(沒有預定義數量的子圖)並保持一個共享的x軸?

在此先感謝

回答

0

首先,生產具有matplotlib動畫,你應該看看FuncAnimation。你會發現很多關於SO帖子關於這個問題,比如:Dynamically updating plot in matplotlib

一般原則是不要重複撥打plt.plot(),而是使用由plot()返回的Line2D對象set_data()功能。換句話說,在你的代碼的第一部分,你實例化一個空的劇情對象

l, = plt.plot([],[]) 

,然後,當你需要更新你的情節,你保持相同的對象(不清除軸,做沒有做出新plot()調用),簡單地更新其內容:

l.set_data(X,Y) 
# alternatively, if only Y-data changes 
l.set_ydata(Y) # make sure that len(Y)==len(l.get_xdata())! 

編輯:這裏是在3軸與共享x軸,就像你正在試圖做

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib.animation import FuncAnimation 

N_points_to_display = 20 
N_lines = 3 
line_colors = ['r','g','b'] 

fig, axs = plt.subplots(N_lines, 1, sharex=True) 
my_lines = [] 
for ax,c in zip(axs,line_colors): 
    l, = ax.plot([], [], c, animated=True) 
    my_lines.append(l) 

def init(): 
    for ax in axs: 
     ax.set_xlim((0,N_points_to_display)) 
     ax.set_ylim((-1.5,1.5)) 
    return my_lines 

def update(frame): 
    #generates a random number to simulate new incoming data 
    new_data = np.random.random(size=(N_lines,)) 
    for l,datum in zip(my_lines,new_data): 
     xdata, ydata = l.get_data() 
     ydata = np.append(ydata, datum) 
     #keep only the last N_points_to_display 
     ydata = ydata[-N_points_to_display:] 
     xdata = range(0,len(ydata)) 
     # update the data in the Line2D object 
     l.set_data(xdata,ydata) 
    return my_lines 

anim = FuncAnimation(fig, update, interval=200, 
        init_func=init, blit=True) 
一個小例子,

enter image description here

+0

你能給出一個最小的工作示例或鏈接到一個嗎? – Daniel

+0

@Daniel我有一點額外的時間,並增加了一個最小的例子,共3個共享x軸 –