Python/Matplotlib实现雨点图动画

Python,Matplotlib实现雨点图动画

关键点

  • win10安装ffmpeg
  • animation函数使用
  • update函数

win10安装ffmpeg

因为最后要将动画图保存为.mp4格式,要用到ffmpeg,去官网下载,我az下载的是windows64bit static版本的,下载后解压到软件安装常用路径,并将ffmpeg路径添加到环境变量(这个方法在最后没用,但还是添加一下)

animationa函数

准确来说是animation.FuncAnimation函数

常用参数:
animation.FuncAnimation(fig,func,frames,init_func,interval)
fig:matplotlib.figure.Figure
func:每一帧都被调用,函数的第一个参数就是下一个参数frames里的value
frames:iterable,可以是整数,整数的话等同于传递range(frames)

init_func:初始化函数,就是fig的最初设置
interval:Delay between frames in milliseconds. Defaults to 200.

update函数

这个函数涉及到每一帧变化所绘制图形里参数的变化,比如例程中的雨点大小,颜色,位置等(散点图scatter绘制),具体看代码

程序实现

最初找到了例程的基于BSD协议的,经过一些自己的修改,所以我也在代码中贴上该协议

# -----------------------------------------------------------------------------
# Copyright (c) 2015, Nicolas P. Rougier. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib import animation
import os

#确定ffmpeg.exe的位置,试过加在环境变量里但依然提示找不到MovieWriter,最后这个方法解决了,在Python2.7版本路径名前面要声明编码是unicode的,而在Python3中有无均可,这是2.X和3.x版本的一个编码方面的区别
plt.rcParams['animation.ffmpeg_path'] = u"D:\\Applications\\ffmpeg-20170503-a75ef15-win64-static\\bin\\ffmpeg.exe"

#这里改变当前工作路径,方便下面保存文件的时候自动保存到该路径下面
os.chdir("d:\\Files\\python\\matplotlib") 

# No toolbar
matplotlib.rcParams['toolbar'] = 'None'

# New figure with white background
fig = plt.figure(figsize=(6,6), facecolor='white')

# New axis over the whole figureand a 1:1 aspect ratio
# ax = fig.add_axes([0,0,1,1], frameon=False, aspect=1)
ax = fig.add_axes([0.005,0.005,0.990,0.990], frameon=True, aspect=1)

# Number of ring
n = 50
size_min = 50
size_max = 50*50

# Ring position ,圆环位置,范围在[0,1]之间
P = np.random.uniform(0,1,(n,2))

# Ring colors环的颜色
C = np.ones((n,4)) * (0,1,0,1)

#C = np.ones((n,3)) * (1,0,1)
# Alpha color channel goes from 0 (transparent) to 1 (opaque)
# 透明度,数值在[0,1]之间
C[:,2] = np.linspace(0,1,n)

# Ring sizes环的大小,范围在[50,2500]
S = np.linspace(size_min, size_max, n)

# Scatter plot
# 散点图绘制
scat = ax.scatter(P[:,0], P[:,1], s=S, lw = 0.5,
                  edgecolors = C, facecolors='None')

# Ensure limits are [0,1] and remove ticks
#保证x,y的范围在[0,1]之间,移除坐标轴标记
ax.set_xlim(0,1), ax.set_xticks([])
ax.set_ylim(0,1), ax.set_yticks([])


def update(frame):
    global P, C, S

    # Every ring is made more transparent每个环变得更透明
    C[:,3] = np.maximum(0, C[:,3] - 1.0/n)

    # Each ring is made larger每个环都比原来的大
    S += (size_max - size_min) / n

    # Reset ring specific ring (relative to frame number)
    i = frame % 50   
    P[i] = np.random.uniform(0,1,2) # P[i] = P[i,:],同时改变了x,y两个位置的值
    S[i] = size_min #从最小的形状开始
    C[i,3] = 1      #设置透明度为1 

    # Update scatter object
    # 更新scatter绘图对象的属性,例如edgecolors,sizes,offsets等
    scat.set_edgecolors(C)  #设置边缘颜色
    scat.set_sizes(S)       #设置大小
    scat.set_offsets(P)     #设置偏置
    return scat,

animate = FuncAnimation(fig, update, frames = 300,interval=70)#interval是每隔70毫秒更新一次,可以查看help

FFwriter = animation.FFMpegWriter(fps=20)   #frame per second帧每秒

animate.save('rain.mp4', writer=FFwriter,dpi=360)#设置分辨率
plt.show()

这里写图片描述

生成的是mp4,把他转化成了文件很小的gif显示了一下效果,保存格式为gif的好像不行,没认真研究过,而且CSDN上传的GIF动图也不能超过2M,~坑

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值