[Python] 纯文本查看 复制代码
@author: fuzhuo
"""
#第一部分 引用数据库
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
#第二部分 创建绘图窗口及相关设置
fig=plt.figure(figsize=(10,10))
ax=fig.add_axes([0,0,1,1],frameon=False)
#创建指定大小的绘图窗口,窗口无框(所绘制图形对象大小等于最终图片对象的大小)
#【0,0,1,1】分别代表所创建的Axes对象的相对于fig的left,bottom,width,height;
#这些数值的取值范围均在0到1之间。
ax.set_xlim(0,1),ax.set_xticks([])
ax.set_ylim(0,1),ax.set_yticks([])
#完全自定义坐标轴刻度和刻度值
#第三步 设置雨滴相关数值
n_drops=50
#雨滴个数等于50
rain_drops=np.zeros(n_drops,\
dtype=[('position',float,2),('size',float,1),\
('growth',float,1),('color',float,4)])
#数据中包括四部分,eg:position中是两个浮点数 color中是四个浮点数
#其中位置position中是两个浮点数,是因为雨滴所在平面为二维平面
#而颜色color中四个浮点数代表四个edgecolor,在动画模拟中,按照顺序变化,才能显示出雨滴的效果。
rain_drops['position']=np.random.uniform(0,1,(n_drops,2))
rain_drops['growth']=np.random.uniform(50,200,n_drops)
#以随机数初始化raindrops的位置和生长率
#uniform(x,y,n)随机生成n个实数,他们在(x,y)范围内。
print(rain_drops)
#打印下来这些数据
#第四部分 构建在雨滴发展过程中我们将在动画中更新的散点。
scat=ax.scatter(rain_drops['position'][:,0],rain_drops['position'][:,1],\
s=rain_drops['size'],lw=0.5,edgecolors=rain_drops['color'],\
facecolors='none')
#其中facecolor除了none外,还可以设置为其他颜色,eg:red,green,black,yellow,等等
#第五部分 定义函数
def update(frame_number):
#获得一个索引,以便我们可以重新生成之前的雨滴
#get an index which we can use to re-spawn the oldest raindrop
current_index=frame_number%n_drops
#随着时间的推移,使所有的颜色更加透明
rain_drops['color'][:,3]-=1.0/len(rain_drops)
rain_drops['color'][:,3]=np.clip(rain_drops['color'][:,3],0,1)
#使所有的圈更大
rain_drops['size']+=rain_drops['growth']
#选中一个新的位置,重新设定其大小,颜色,生长因素。
rain_drops['position'][current_index]=np.random.uniform(0,1,2)
rain_drops['size'][current_index]=5
rain_drops['color'][current_index]=(0,0,0,1)
rain_drops['growth'][current_index]=np.random.uniform(50,200)
#使用新的颜色,大小和位置更新散点集合
scat.set_edgecolors(rain_drops['color'])
scat.set_sizes(rain_drops['size'])
scat.set_offsets(rain_drops['position'])
#第六部分 创建动画
#在其中使用更新函数来作为动画导演,interval表示间隔
ainmation=FuncAnimation(fig,update,interval=10)
plt.show()
#而要将其显示成为动画效果,需要在IPython console中输入代码“%matplotlib qt5”两至三遍
#每输入一次,按一下回车,然后,单击“Run”,就会有雨滴落在青青草地啦~