Matplotlib - 定時器



在一般的計算機程式設計中,**定時器**指的是一種允許使用者在預定義的時間間隔內安排特定任務或程式碼片段執行的機制。定時器在各種應用程式中都很有用,可以實現重複操作的自動化、定期更新或基於時間相關條件觸發事件。

Matplotlib 中的定時器

Matplotlib 定時器是強大的功能,使您能夠將週期性事件整合到繪圖中。並且設計為獨立於特定的圖形使用者介面 (GUI) 後端工作。

要利用 Matplotlib 定時器功能,**figure.canvas.new_timer()** 函式作為將定時器與各種 GUI 事件迴圈整合的關鍵元件。雖然它的呼叫簽名可能看起來不尋常,但由於這種理解,呼叫簽名至關重要(如果您的回撥函式不接受引數或關鍵字引數,則需要顯式指定空序列和字典)。

以下是語法:

語法

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

此語法建立一個間隔為 5 秒的定時器,演示了定時器與 Matplotlib 繪圖的整合。

示例

這是一個示例,它演示了在 Matplotlib 中使用定時器的簡單用法。它設定了一個定時器,每 5 秒將“Matplotlib 定時器事件”列印到控制檯。這展示瞭如何在繪圖中使用定時器執行週期性任務。

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

輸出

執行上述程式後,您將獲得以下輸出:

timers_ex1
Matplotlib Timer Event
Matplotlib Timer Event
Matplotlib Timer Event
Matplotlib Timer Event
Matplotlib Timer Event
Matplotlib Timer Event

觀看下面的影片以觀察此示例的工作原理。

timers_ex1 gif

用於即時更新的定時器

定時器可用於在繪圖中實現即時更新,增強視覺化的動態特性。

示例

在示例中,定時器用於以 500 毫秒的間隔更新圖形的標題,其中包含當前時間戳。這表明,如何在視覺化中使用定時器進行動態、時間敏感的更新。

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

輸出

執行上述程式後,您將獲得以下輸出:

timers_ex2

觀看下面的影片以觀察此示例的工作原理。

timers_ex2 gif

帶定時器的動畫布朗運動

在更高階的場景中,我們利用定時器的優勢來動畫化一個二維布朗運動,建立一個隨著時間推移而生成的視覺動態繪圖。

示例

此示例演示了定時器在建立動畫視覺化中的應用。

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

輸出

執行上述程式後,您將獲得一個帶有動畫的圖形:

timers_ex3

觀看下面的影片以觀察此示例的工作原理。

timers_ex3 gif
廣告