87.md 1.4 KB
Newer Older
W
wizardforcel 已提交
1
# Matplotlib 更新绘图
W
init  
wizardforcel 已提交
2 3 4

> 原文: [https://pythonspot.com/matplotlib-update-plot/](https://pythonspot.com/matplotlib-update-plot/)

W
wizardforcel 已提交
5
更新 [**matplotlib**](https://pythonspot.com/matplotlib/) 绘图非常简单。 创建数据,绘图并循环更新。
W
wizardforcel 已提交
6 7

启用交互模式至关重要:`plt.ion()`。 这控制是否通过每个`draw()`命令重绘图形。 如果它为`False`(默认值),则该图不会自动更新。
W
init  
wizardforcel 已提交
8

W
wizardforcel 已提交
9
## 更新绘图示例
W
init  
wizardforcel 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

复制下面的代码以测试交互式绘图。

```py

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10*np.pi, 100)
y = np.sin(x)

plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'b-')

for phase in np.linspace(0, 10*np.pi, 100):
line1.set_ydata(np.sin(0.5 * x + phase))
fig.canvas.draw()

```

![matplotlib-update](img/a27d316530f4f9a8d71898076641b9ef.jpg)

Capture of a frame of the program above

## 说明

我们使用以下方法创建要绘制的数据:

```py

x = np.linspace(0, 10*np.pi, 100)
y = np.sin(x)

```

使用以下命令打开交互模式:

```py

plt.ion()

```

W
wizardforcel 已提交
55
配置图(`"b-"`表示蓝线):
W
init  
wizardforcel 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75

```py

fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'b-')

```

最后循环更新:

```py

for phase in np.linspace(0, 10*np.pi, 100):
line1.set_ydata(np.sin(0.5 * x + phase))
fig.canvas.draw()

```

[下载示例](https://pythonspot.com/download-matplotlib-examples/)