如何动画化并更新横轴?

3 投票
1 回答
554 浏览
提问于 2025-04-18 00:44

我正在尝试使用matplotlib来显示一些“实时”的数据。最好是让横轴显示最近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

我会用稍微不同的方法来处理这个问题。不过,我不确定这是否是最好的办法。欢迎大家提出意见和建议。

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()

撰写回答