Matplotlib - 關閉事件



在程式設計和軟體設計的背景下,事件指的是軟體識別的一個動作或事件。這些事件可以由系統、使用者輸入或其他來源發起,並由軟體進行處理。

具體來說,關閉事件是在軟體介面中關閉圖形時觸發的事件。此事件表示與圖形相關的圖形表示或視窗的終止或關閉,並提醒軟體相應地做出響應。

Matplotlib 中的關閉事件

Matplotlib 提供了一套處理事件的工具,其中包括處理關閉事件的能力。Matplotlib 中的關閉事件發生在關閉圖形視窗時,會在 Python 指令碼中觸發特定操作。透過連線到 close_event,您可以執行自定義程式碼以響應圖形的關閉。

在本教程中,我們將探討如何在 Matplotlib 中使用關閉事件來增強互動式繪圖。

示例

這是一個簡單的示例,當用戶關閉圖形時顯示一條訊息。

import matplotlib.pyplot as plt

def on_close(event):
   print('The Figure is Closed!')

fig, ax = plt.subplots(figsize=(7, 4))
ax.annotate('X', xy=(1, 1), xytext=(0.9, 0.65), fontsize=20,
   arrowprops=dict(facecolor='red'),
   horizontalalignment='left',
   verticalalignment='bottom')

fig.canvas.mpl_connect('close_event', on_close)

ax.text(0.15, 0.5, 'Close This Figure!', dict(size=30))
plt.show()

輸出

執行上述程式碼後,我們將得到以下輸出:

close_event_ex1

關閉上述輸出圖形後,控制檯將顯示以下訊息:

The Figure is Closed!

檢測已關閉的座標軸

當在一個圖形中處理多個座標軸時,需要確定特定座標軸是否已關閉,可以使用 Matplotlib 中的關閉事件操作。

示例

這是一個演示如何使用 Matplotlib 中的關閉事件來確定特定座標軸是否已關閉的示例。

import matplotlib.pyplot as plt

# Function to handle the event 
def on_close(event):
   event.canvas.figure.axes[0].has_been_closed = True
   print('The Figure is Closed!')

# Create the figure 
fig, ax = plt.subplots(figsize=(7, 4))
ax.set_title('Detecting Closed Axes')
ax.has_been_closed = False
ax.plot(range(10))

# connect the event with the callable function
fig.canvas.mpl_connect('close_event', on_close)

plt.show()
print('Check the attribute has_been_closed:', ax.has_been_closed)

輸出

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

close_event_ex2

關閉上述輸出圖形後,控制檯將顯示以下訊息:

The Figure is Closed!
Check the attribute has_been_closed: True

關閉後繼續執行程式碼

在某些情況下,即使在圖形關閉後(關閉事件觸發),也可能需要程式碼繼續執行。這對於後臺程序或動畫尤其有用。

示例

以下示例演示如何在關閉圖形後繼續執行程式碼。

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

close_flag = 0

def handle_close(evt):
   global close_flag
   close_flag = 1
   print('The Figure is Closed!')

# Activate interactive mode
plt.ion()  
fig, ax = plt.subplots()

# listen to close event
fig.canvas.mpl_connect('close_event', handle_close)

# Generating x values 
x = np.arange(0, 2*np.pi, 0.01)
y = np.sin(x)

# Plotting the initial sine curve
line, = ax.plot(x, y)
ax.legend([r'$\sin(x)$'])

# Function to update the plot for each frame of the animation
def update(frame):
   line.set_ydata(np.sin(x + frame / 50))
   return line

t = 0
delta_t = 0.1
while close_flag == 0:
   if abs(t - round(t)) < 1e-5:
      print(round(t))
    
   x = x + delta_t
   y = y - delta_t

   # Creating a FuncAnimation object
   ani = animation.FuncAnimation(fig=fig, func=update, frames=40, interval=30)

   # draw the figure
   fig.canvas.draw() 
   fig.canvas.flush_events() 

   # wait a little bit of time
   time.sleep(delta_t) 

   t += delta_t

   if close_flag == 1:
      break

print('ok')

輸出

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

close_event_ex3

關閉上述輸出圖形後,控制檯將顯示以下訊息:

0
1
2
3
4
5
The Figure is Closed!
ok

觀看下面的影片,瞭解此處關閉事件功能的工作方式。

close_event_ex3 gif
廣告