数据可视化-matplotlib animation 绘制动画

2019-08-09  本文已影响0人  洗洗睡吧i

1. 用 matplotlib animation 绘制动画

ref: https://matplotlib.org/3.1.1/api/animation_api.html

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

# 数据集:X轴数据固定;Y轴的数据更新
X = np.arange(0, 10, 0.01)  # X shape: (N,)
Ys = [np.sin(X + k / 10) for k in range(100)]  # Ys shape: (k, N)


def my_ani(x, ys):
    fig, ax = plt.subplots()
    ax.set_title('y = sin(x + k/10)')
    ax.set_xlim([0, 10]), ax.set_xlabel('X')
    ax.set_ylim([-1, 1]), ax.set_ylabel('Y')

    line, = ax.plot(x, ys[0])
    ano = plt.annotate('k: 0', (1, 1))

    def animate(i):
        line.set_ydata(ys[i])       # update the y data.
        ano.set_text('k: %d' % i)  # update the annotate.
        return line,

    # animation.FuncAnimation 参数说明
    # fig:          figure 对象
    # func:         动画函数,自定义函数 animate
    # frames:       总帧数
    # interval:     间隔时间,ms
    ani = animation.FuncAnimation(fig, animate, frames=30, interval=50)
    # ani.save('sin_ani.mp4', dpi=300, writer='ffmpeg')     # scoop install ffmpeg
    # ani.save('sin_ani.gif', dpi=300, writer='pillow')     # pip install pillow
    plt.show()


my_ani(X, Ys)

sin_ani.gif

2. 也用 plot 的方法显示动画,保存不太方便

import matplotlib.pyplot as plt
import numpy as np

# 数据集:X轴数据固定;Y轴的数据更新
X = np.arange(0, 10, 0.01)  # X shape: (N,)
Ys = [np.sin(X + k / 10) for k in range(100)]  # Ys shape: (k, N)

plt.ion()
plt.show()
for i in range(len(Ys)):
    plt.cla()

    plt.title('y = sin(x + k/10)')
    plt.xlim(0, 10)
    plt.ylim(-1, 1)
    
    plt.plot(X, Ys[i], 'r', alpha=0.7, linewidth=0.7)
    plt.text(1, 1, 'k: %d' % i)

    plt.draw()
    plt.pause(0.05)  # 间隔时间,s
上一篇 下一篇

猜你喜欢

热点阅读