49

怎样用Python制作好玩的GIF动图

 5 years ago
source link: https://jizhi.im/blog/post/pytogif?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

参考资料: drawing-animated-gifs-with-matplotlib/

之前我们分享过 用Python进行可视化的9种常见方式 。其实我们还能让可视化图形逼格更高一些,今天就分享一下如何让可视化秀起来: 用Python和matplotlib制作GIF图表

假如电脑上没有安装ImageMagick,先去 这里 按照自己的电脑系统下载对应版本,如果我们想用matplotlib的save方法渲染GIF动图,就需要安装ImageMagick。

下图是我们制作的一个动图示例:

MZ3umiv.gif

有两点需要注意: 图表中的散点不会动,会动的是直线。 X轴标题每一帧都在变化。

下面是我们制作上面GIF图的代码:

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

fig, ax = plt.subplots()
fig.set_tight_layout(True)

# 询问图形在屏幕上的大小和DPI(每英寸点数)
# 注意当把图形保存为文件时,需要为此单独再提供一个DPI
print('fig size: {0} DPI, size in inches {1}'.format(
    fig.get_dpi(), fig.get_size_inches()))

# 绘制一个保持不变(不会被重新绘制)的散点图以及初始直线
x = np.arange(0, 20, 0.1)
ax.scatter(x, x + np.random.normal(0, 3.0, len(x)))
line, = ax.plot(x, x - 5, 'r-', linewidth=2)

def update(i):
    label = 'timestep {0}'.format(i)
    print(label)
# 更新直线和轴(用一个新X轴标签)
    # 以元组形式返回这一帧需要重新绘制的物体
    line.set_ydata(x - 5 + i)
    ax.set_xlabel(label)
    return line, ax

if __name__ == '__main__':
    # 会为每一帧调用Update函数
    # 这里FunAnimation设置一个10帧动画,每帧间隔200ms
    anim = FuncAnimation(fig, update, frames=np.arange(0, 10), interval=200)
    if len(sys.argv) > 1 and sys.argv[1] == 'save':
        anim.save('line.gif', dpi=80, writer='imagemagick')
    else:
        # Plt.show()会一直循环动画
        plt.show()

如果你想换个再酷炫点的主题,可以用seaborn库,只需添加:

import seaborn

那么就会得到下面这张GIF图:

7ZJ3qeV.gif

稍微提醒一下:虽然我们这里的GIF图只有10帧,图形内容也很简单,但每一帧仍有160k左右。因为GIF动图不使用跨帧压缩,所以这就让帧比较长的GIF图变得很大。将帧数尽量减少,并且让每一帧的图像再小一点(通过在matplotlib中调整图形大小或DPI)能或多或少有助于缓解这个问题。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK