2015-07-22 71 views
4

我需要绘制很多行,并且我想在计算它们时显示它们。代码看起来像这样:动态重叠显示

x = arange(100000) 
for y in range(100000): 
    ax.plot(x*y) 
    draw() 

现在,正如你可以想象的,这个速度非常快。我想我可以做的是绘图,将绘图保存到缓冲区,清除绘图,放下缓冲区作为背景,然后绘制下一行。这样,我不会得到如此多的Line2D对象。有没有人有任何想法?

回答

4

看来你需要matplotlib.animation功能。 animation examples

编辑:添加了我自己的版本更简单的示例代码。

import random 
from matplotlib import pyplot as plt 
from matplotlib import animation 

def data_generator(t): 
    if t<100: 
     return random.sample(range(100), 20) 

def init(): 
    return plt.plot() 

def animate(i): 
    data = data_generator(i) 
    return plt.plot(data, c='k') 

fig = plt.figure() 
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=1000, interval=1000, blit=True) 
plt.show() 

EDIT2:多行实时更新的版本。

import random 
from matplotlib import pyplot as plt 
from matplotlib import animation 

def data_generator_1(t): 
    if t<100: 
     x1.append(t) 
     y1.append(random.randint(1, 100)) 

def data_generator_2(t): 
    if t<100: 
     x2.append(t) 
     y2.append(random.randint(1, 100)) 

def init(): 
    global x1 
    global y1 
    x1 = [] 
    y1 = [] 

    global x2 
    global y2 
    x2 = [] 
    y2 = [] 

    l1, l2 = plt.plot(x1, y1, x2, y2) 
    return l1, l2 

def animate(i): 
    data_generator_1(i) 
    data_generator_2(i) 
    l1, l2 = plt.plot(x1, y1, x2, y2) 
    plt.setp(l1, ls='--', c='k') 
    plt.setp(l2, c='gray') 
    return l1, l2 

fig = plt.figure() 
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=1000, interval=1000, blit=True) 
plt.show() 

enter image description here

我敢肯定,有策划这种动画没有全局变量的方法很多。这只是快速试用,向你展示你想要什么的可能性。

我不知道你的第一个评论认为ipython/vanilla脚本问题。所有示例都在普通编辑器(而不是ipython)上编码。也许有matplotlib版本的差异。

+0

有什么奇怪的是,这个运行完全按照我希望它在IPython的笔记本,而不是从命令行的脚本文件运行。不幸的是,我需要后者。 – BossColo

+0

我还从数据生成器接收需要绘制的两个数据产品。我大概可以自己弄清楚,但如果您有任何见解,我将不胜感激! – BossColo

+0

对我的第一条评论的澄清:第一条线绘制在图上,但后面的每个绘图都会在下一个绘图之前清除。 – BossColo

0

或者,如果您使用的是笔记本的IPython,您可以使用IPython的显示功能:

from IPython import display 
import matplotlib.pyplot as plt 
import numpy as np 
%matplotlib 

x = np.arange(100) 

for y in np.arange(100): 
    fig, ax = plt.subplots(1,1, figsize=(6,6)) 
    ax.plot(x * y) 
    ax.set_ylim(0, 10000) # to keep the axes always the same 
    display.clear_output(wait=True) 
    display.display(fig) 
    plt.close() 

如果你想在任何时候说,10日线在同一时间画了一个,你可以这样做:

x = np.arange(100) 
fig, ax = plt.subplots(1,1, figsize=(6,6)) 
for y in np.arange(100):   
    ax.plot(x*y) 
    ax.set_ylim(0,10000) 
    display.clear_output(wait=True) 
    display.display(fig) 
    if y > 10:   # from the 10th iteration, 
     ax.lines.pop(0) # remove the first line, then the 2nd, etc.. 
         # but it will always be in position `0` 
plt.close() 

HTH