如何动画和更新水平轴?

时间:2014-03-31 20:04:45

标签: python matplotlib

我正在尝试使用matplotlib来显示一些" live"数据。我希望水平轴显示最近10秒左右的运行间隔。

下面的程序演示了我之后的所作所为。但是,这个程序并没有以两种方式做我想做的事。

首先,我希望水平轴显示绝对时间(目前,它显示时间,以秒为单位,相对于" tNow")。理想情况下,水平轴应不断更新。

其次,出于某些原因我不明白,对所提取信号的第一次评估是持久性的;我只对"移动"感兴趣信号;静态信号是一个人工制品。我怎么能摆脱它?

不幸的是,我对matplotlib并不是非常好。因此,任何帮助将不胜感激。

#! /usr/bin/env python

import time

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

def update_line(num, line1, line2):

    tNow = time.time()

    t = np.linspace(tNow - 10.0, tNow, 200)

    f1 = 0.5 # Hz
    f2 = 0.3 # Hz

    line1.set_data(t - tNow, np.sin(2 * np.pi * f1 * t))
    line2.set_data(t - tNow, np.sin(2 * np.pi * f2 * t))

    return (line1, line2)

(fig, axes_list) = plt.subplots(2, 1)

axes1 = axes_list[0]
axes2 = axes_list[1]

line1, = axes1.plot([], [], 'r-')
line2, = axes2.plot([], [], 'b-')

for ax in [axes1, axes2]:
    ax.set_xlim(-10, 0)
    ax.set_ylim(-1, 1)
    #ax.set_xlabel('x')
    #ax.set_ylabel('y')
    #ax.set_title('test')

animation = animation.FuncAnimation(fig, update_line, 250, fargs = (line1, line2), interval = 0, blit = True)

# Enter the event loop
fig.show()

1 个答案:

答案 0 :(得分:0)

我会稍微接近它。但是,我不确定这是不是最好的方法。欢迎提出意见和建议

import time
import datetime
import numpy as np
import matplotlib.pyplot as plt

F1 = 0.5 # Hz
F2 = 0.3 # Hz

def update_line(tstart, axes):

    for ax in axes:
        # Remove old lines
        ax.lines.pop()

    # Plot new lines
    axes[0].plot(t, np.sin(2 * np.pi * F1 * np.array(t)), 'r-')
    axes[1].plot(t, np.sin(2 * np.pi * F2 * np.array(t)), 'b-')

# relabel the x tick marks to be absolute time
def show_abs_time(abs_start, axes):

    for ax in axes:
        tick_labels = []
        ticks = ax.get_xticks()

        # using the relative time for each tick mark, add it to the absolute time
        for rel_time in ticks:
            abs_time = abs_start + datetime.timedelta(0,rel_time) 
            tick_labels.append(abs_time.strftime("%X"))

        ax.set_xticklabels(tick_labels)


if __name__ == "__main__":
    plt.ion()
    plt.close("all")

    (fig, axes) = plt.subplots(2, 1)

    # Initial Plot configuration 
    for ax in axes:
        ax.set_xlim(0, 10)
        ax.set_ylim(-1, 1)
        ax.set_xlabel('x')
        ax.set_ylabel('y')
        ax.set_title('test')

    tstart = time.time()
    delta_t = 0
    t = []
    abs_start = datetime.datetime.strptime(time.strftime("%X"), "%H:%M:%S")  

    axes[0].plot([], [], 'r-')
    axes[1].plot([], [], 'b-')

    plt.show()

    while delta_t < 20 :

        tNow = time.time()
        delta_t = tNow - tstart
        t.append(delta_t)
        update_line(t, axes)

        # Once your time extends past a certain point, update the x axis
        if delta_t > 9:
            for ax in axes:
                ax.set_xlim(delta_t-9,delta_t + 1)

        # redo the x ticks to be absolute time
        show_abs_time(abs_start, axes)

        # update the plots
        plt.draw()