2017-08-29 26 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轴 –