# 如何在 Matplotlib 中自動執行圖更新

Suraj Joshi 2023年1月30日

## `canvas.draw()` 和 `canvas_flush_events()`

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

x = np.linspace(0, 10, 100)
y = np.cos(x)

plt.ion()

figure, ax = plt.subplots(figsize=(8, 6))
(line1,) = ax.plot(x, y)

plt.title("Dynamic Plot of sinx", fontsize=25)

plt.xlabel("X", fontsize=18)
plt.ylabel("sinX", fontsize=18)

for p in range(100):
updated_y = np.cos(x - 0.05 * p)

line1.set_xdata(x)
line1.set_ydata(updated_y)

figure.canvas.draw()

figure.canvas.flush_events()
time.sleep(0.1)
``````

`plt.ion()` 開啟互動模式。如果未呼叫，則該圖不會更新。

`canvas.draw()` 是一種基於 JavaScript 來顯示圖形的方法，而 `canvas.flush_events()` 也基於 JavaScript 來清除圖形。

## `plt.draw()` 更新 Matplotlib 中的圖

### 使用 `plt.clf()`

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

x = np.linspace(0, 10, 100)
y = np.cos(x)

plt.ion()

figure, ax = plt.subplots(figsize=(8, 6))
(line1,) = ax.plot(x, y)

plt.title("Dynamic Plot of sinx", fontsize=25)

plt.xlabel("X", fontsize=18)
plt.ylabel("sinX", fontsize=18)

for p in range(100):
updated_y = np.cos(x - 0.05 * p)

line1.set_xdata(x)
line1.set_ydata(updated_y)

figure.canvas.draw()

figure.canvas.flush_events()
time.sleep(0.1)
``````

### 使用 `fig.clear()`

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

x = np.linspace(0, 10, 100)
y = np.cos(x)

fig = plt.figure()

for p in range(50):
p = 3
updated_x = x + p
updated_y = np.cos(x)
plt.plot(updated_x, updated_y)
plt.draw()
x = updated_x
y = updated_y
plt.pause(0.2)
fig.clear()
``````

Suraj Joshi is a backend software engineer at Matrice.ai.