matplotlib绘制散点动图
时间: 2023-07-12 16:11:36 浏览: 185
要在matplotlib中绘制散点动图,需要使用动画功能。具体步骤如下:
1. 导入必要的库
```python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
```
2. 创建一个空的散点图
```python
fig, ax = plt.subplots()
scatter = ax.scatter([], [], animated=True)
```
3. 定义一个函数用于更新散点图
```python
def update(frame):
# 更新散点图的数据
x = np.random.rand(100)
y = np.random.rand(100)
colors = np.random.rand(100)
sizes = 1000 * np.random.rand(100)
scatter.set_offsets(np.c_[x, y])
scatter.set_color(colors)
scatter.set_sizes(sizes)
# 返回散点图对象
return scatter,
```
4. 创建一个动画对象
```python
animation = FuncAnimation(fig, update, frames=range(100), interval=50, blit=True)
```
5. 显示动画
```python
plt.show()
```
完整代码如下:
```python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
scatter = ax.scatter([], [], animated=True)
def update(frame):
x = np.random.rand(100)
y = np.random.rand(100)
colors = np.random.rand(100)
sizes = 1000 * np.random.rand(100)
scatter.set_offsets(np.c_[x, y])
scatter.set_color(colors)
scatter.set_sizes(sizes)
return scatter,
animation = FuncAnimation(fig, update, frames=range(100), interval=50, blit=True)
plt.show()
```
阅读全文
相关推荐















