Matplotlib 简明教程

Matplotlib - Timers

在通用的计算机编程中, timers 指的是允许用户在预定义的时间间隔内安排执行特定任务或代码片段的机制。计时器对于各种应用程序都很有用,它可以实现重复操作、定期更新或基于时间相关条件触发事件的自动化。

In general computer programming, timers are refers to a mechanism that allows users to schedule the execution of a specific task or code snippet at predefined intervals. Timers are useful for various applications, enabling the automation of repetitive actions, periodic updates, or the triggering of events based on time-related conditions.

Timers in Matplotlib

Matplotlib 计时器是强大的功能,它使您能够将定期事件集成到图表中。并且被设计为独立于特定图形用户界面 (GUI) 后端工作。

Matplotlib timers are powerful features that enable you to integrate periodic events into the plots. And designed to work independently of specific graphical user interface (GUI) backends.

若要利用 Matplotlib 计时器功能, figure.canvas.new_timer() 函数将作为集成功能与各种 GUI 事件循环的关键组件。尽管它的调用签名可能看起来不太习惯,但由于这种理解,调用签名至关重要(如果你调用的函数不使用参数或关键字参数,则需要明确指定空的序列和字典)。

To utilize the Matplotlib timers feature, the figure.canvas.new_timer() function works as a key component to integrate timers with various GUI event loops. While its call signature may appear unconventional, due to this understanding the call signature is crucial (you need to explicitly specify the empty sequences and dictionaries if your call back function(s) don’t take arguments or keyword arguments).

以下是语法 −

Here is the syntax −

Syntax

timer = figure.canvas.new_timer(interval=5000, callbacks=[(callback_function, [], {})])
timer.start()

该语法创建了一个间隔为 5 秒的计时器,演示了如何将计时器集成到 Matplotlib 的图表中。

This syntax creates a timer with a 5-second interval, demonstrating the timer’s integration into Matplotlib plots.

Example

以下是一个示例,演示了在 Matplotlib 中简单使用计时器。它设置了一个计时器,每 5 秒在控制台上打印“Matplotlib Timer Event”。这展示了如何将计时器用于图表中的周期性任务。

Here is an example, That demonstrates a simple usage of timers in Matplotlib. It sets up a timer to print "Matplotlib Timer Event" to the console every 5 seconds. This showcases how timers can be employed for periodic tasks within plots.

import matplotlib.pyplot as plt

# Function to handle the timer event
def handle_timer_event():
   print('Matplotlib Timer Event')

# Create a new Matplotlib figure and axis
custom_fig, custom_ax = plt.subplots(figsize=(7, 4))

# Create a timer with a 5000 milliseconds interval
custom_timer = custom_fig.canvas.new_timer(interval=5000, callbacks=[(handle_timer_event, [], {})])

# Start the timer
custom_timer.start()
plt.show()

在执行上述程序后,你将获得以下输出 -

On executing the above program you will get the following output −

timers ex1
Matplotlib Timer Event
Matplotlib Timer Event
Matplotlib Timer Event
Matplotlib Timer Event
Matplotlib Timer Event
Matplotlib Timer Event

观看下面的视频来观察此示例的工作。

Watch the video below to observe the works of this example.

timers ex1

Timer for Real-Time Updates

计时器可用于在图表内实现实时更新,从而增强可视化的动态特性。

Timers can be used to achieve real-time updates within a plot, enhancing the dynamic nature of visualizations.

Example

在该示例中,一个计时器用于使用当前时间戳以 500 毫秒的间隔更新数字的标题。它显示了如何将计时器用于可视化中的动态、受时间制约的更新。

In the example, a timer is used to update the title of a figure with the current timestamp at intervals of 500 milliseconds. Which shows that, how timers can be used for dynamic, time-sensitive updates in visualizations.

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

# Function to update the title with the current timestamp
def update_title(axes):
   axes.set_title(datetime.now())
   axes.figure.canvas.draw()

# Create a Matplotlib figure and axis
fig, ax = plt.subplots(figsize=(7, 4))

# Generate sample data
x = np.linspace(0, 10, 100)
ax.plot(x, np.sin(x))

# Create a new timer with an interval of 500 milliseconds
timer = fig.canvas.new_timer(interval=500)

# Add the update_title function as a callback to the timer
timer.add_callback(update_title, ax)

# Start the timer
timer.start()
plt.show()

在执行上述程序后,你将获得以下输出 -

On executing the above program you will get the following output −

timers ex2

观看下面的视频来观察此示例的工作。

Watch the video below to observe the works of this example.

timers ex2

Animated Brownian Walk with Timer

在更高级的场景中,我们使用计时器的优点以动画方式呈现二维布朗运动,从而创建随时间推移产生的具有视觉动态效果的图表。

In a more advanced scenario, we use the advantages of timers to animate a 2D Brownian walk, creating a visually dynamic plot that produces over time.

Example

此示例演示了在创建动画可视化中使用计时器。

This example demonstrates the application of timers in creating animated visualizations.

import numpy as np
import matplotlib.pyplot as plt

# Callback function for the timer to update line data
def update_line_data(line, x_data, y_data):
   x_data.append(x_data[-1] + np.random.normal(0, 1))
   y_data.append(y_data[-1] + np.random.normal(0, 1))
   line.set_data(x_data, y_data)
   line.axes.relim()
   line.axes.autoscale_view()
   line.axes.figure.canvas.draw()
# Initial data points
x_coords, y_coords = [np.random.normal(0, 1)], [np.random.normal(0, 1)]

# Create a Matplotlib figure and axis
fig, ax = plt.subplots(figsize=(7, 4))
line, = ax.plot(x_coords, y_coords, color='aqua', marker='o')

# Create a new timer with a 100-millisecond interval
animation_timer = fig.canvas.new_timer(interval=1000, callbacks=[(update_line_data, [line, x_coords, y_coords], {})])
animation_timer.start()

# Display the animated plot
plt.show()

在执行上述程序后,你将获得一个带有动画的图形 -

On executing the above program you will get a figure with animation −

timers ex3

观看下面的视频来观察此示例的工作。

Watch the video below to observe the works of this example.

timers ex3