欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python绘制双动态散点图并保存

程序员文章站 2022-03-09 20:23:03
...

例程:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random

fig, ax = plt.subplots()
line,=ax.plot([],[],marker='o',markeredgewidth=9)
line_1,=ax.plot([],[],marker='o',markeredgewidth=9)#定义两个line对象
x=[random.randint(1,50) for i in range(100)]#随机生成100个数
y=[random.randint(1,50) for i in range(100)]
xdata=[]
ydata=[]

def data_gen(t=0):
    while t<99:
        t+=1
        yield t

def animate(i):
    xdata.append(x[i])
    ydata.append(y[i])
    line.set_data(xdata,ydata)  # update the data.
    line.set_markerfacecolor('r')
    line.set_markersize(9)
    line.set_linestyle('None')#画散点
    ax.set_xlim(1,50)
    ax.set_ylim(1, 50)
    line_1.set_data(x[i], y[i])  # update the data.
    line_1.set_markerfacecolor('r')
    line_1.set_markersize(9)
    return line,line_1


ani = animation.FuncAnimation(fig, animate,data_gen,interval=400, blit=True)

# ani.save("movie.gif",writer='pillow')#保存为gif
#or
# Writer = animation.writers['ffmpeg']#需安装ffmpeg
# writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
# ani.save("movie.mp4",writer=writer)
plt.show()

如果保存为gif的话,只需要将writer='pillow'即可,如果动画太大需要保存为MP4时,则需要下载ffmpeg,下载地址:https://ffmpeg.zeranoe.com/builds/,详细安装教程:https://www.wikihow.com/Install-FFmpeg-on-Windows