使用Matplotlib制作动图

我们可以使用Matplotlib的animation模块的FuncAnimation类制作动画,你需要提供的只是一个动态更新变化数据的函数。
下面是一个最基本的例子:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

fig = plt.figure()
data = np.random.random((255, 255))
im = plt.imshow(data, cmap='gray')

# animation function.  This is called sequentially
def animate(i):
    data = np.random.random((255, 255))
    im.set_array(data)
    return [im]

anim = animation.FuncAnimation(fig, animate, frames=200, interval=60, blit=True)
plt.show()

这个例子中的animation()函数就是动态更新data数据的函数,注意这个函数必须返回一个集合,所以给[im]将im转变成一个list进行返回。

下面是从一个教程网站看到模拟雨滴落在地面的例子(http://www.labri.fr/perso/nrougier/teaching/matplotlib/),觉得不错,贴过来。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation

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

# New axis over the whole figure, no frame and a 1:1 aspect ratio
ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect=1)

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

# Ring position
pos = np.random.uniform(0, 1, (n,2))

# Ring colors
color = np.ones((n,4)) * (0,0,0,1)
# Alpha color channel geos from 0(transparent) to 1(opaque)
color[:,3] = np.linspace(0, 1, n)

# Ring sizes
size = np.linspace(size_min, size_max, n)

# Scatter plot
scat = ax.scatter(pos[:,0], pos[:,1], s=size, lw=0.5, edgecolors=color, facecolors='None')

# Ensure limits are [0,1] and remove ticks
ax.set_xlim(0, 1), ax.set_xticks([])
ax.set_ylim(0, 1), ax.set_yticks([])

def update(frame):
    global pos, color, size

    # Every ring is made more transparnt
    color[:, 3] = np.maximum(0, color[:,3]-1.0/n)

    # Each ring is made larger
    size += (size_max - size_min) / n

    # Reset specific ring
    i = frame % 50
    pos[i] = np.random.uniform(0, 1, 2)
    size[i] = size_min
    color[i, 3] = 1

    # Update scatter object
    scat.set_edgecolors(color)
    scat.set_sizes(size)
    scat.set_offsets(pos)

    # Return the modified object
    return scat,

anim = animation.FuncAnimation(fig, update, interval=10, blit=True, frames=200)
plt.show()

注意这里的返回值是scat,通过给scat添加一个逗号表示返回一个tuple。

Rain

  • 7
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值