import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as ma
# 初始化构建所有样本
n = 100
balls = np.zeros(n, dtype=[
('position', float, 2),
('size', float, 1),
('growth', float, 1),
('color', float, 4)])
balls['position'] = np.random.uniform(0, 1, (n, 2))
balls['size'] = np.random.uniform(40, 50, n)
balls['growth'] = np.random.uniform(10, 20, n)
balls['color'] = np.random.uniform(0, 1, (n, 4))
# 绘制图像
plt.figure('Bubble', facecolor='lightgray')
plt.title('Bubble', fontsize=16)
sc = plt.scatter(balls['position'][:, 0], balls['position'][:, 1], balls['size'], color=balls['color'])
plt.xticks([])
plt.yticks([])
# 实现动画
def update(number):
# 更新界面, 让每个点不断变大
balls['size'] += balls['growth']
sc.set_sizes(balls['size'])
index = number % n
balls['size'][index] = \
np.random.uniform(40, 70, 1)
balls['position'][index] = \
np.random.uniform(0, 1, (1, 2))
# 更新界面
sc.set_sizes(balls['size'])
sc.set_offsets(balls['position'])
# 每隔三十毫秒,执行一次update函数
anim = ma.FuncAnimation(
plt.gcf(), update, interval=30)
plt.show()
# 使用imagemagick 保存为gif
# 提前 sudo apt-get install imagemagick
anim.save('bubble_animation.gif', writer='imagemagick')
[外链图片转存失败(img-yXtTwZpE-1565424053086)(https://www.exobrain.online/2016/08/12/matplotlib-animation-FuncAnimation/bubble_animation.gif)]