首页 > 编程技术 > python

Python中的图形绘制简单动画实操

发布时间:2022-2-21 17:15 作者:来西瓜

前言:

      Matplotlib 是一个非常广泛的库,它也支持图形动画。 动画工具以 matplotlib.animation 基类为中心,它提供了一个框架,围绕该框架构建动画功能。 主要接口有TimedAnimationFuncAnimation,两者中FuncAnimation是最方便使用的。

1、画螺旋曲线代码

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
  
# create a figure, axis and plot element
fig = plt.figure()
ax = plt.axes(xlim=(-50, 50), ylim=(-50, 50))
line, = ax.plot([], [], lw=2)
  
# initialization function
def init():
    # creating an empty plot/frame
    line.set_data([], [])
    return line,
  
# lists to store x and y axis points
xdata, ydata = [], []
  
# animation function
def animate(i):
    # t is a parameter
    t = 0.1*i
      
    # x, y values to be plotted
    x = t*np.sin(t)
    y = t*np.cos(t)
      
    # appending new points to x, y axes points list
    xdata.append(x)
    ydata.append(y)
      
    # set/update the x and y axes data
    line.set_data(xdata, ydata)
      
    # return line object
    return line,
      
# setting a title for the plot
plt.title('A growing coil!')
# hiding the axis details
plt.axis('off')
  
# call the animator    
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=500, interval=20, blit=True)
  
# save the animation as mp4 video file
anim.save('animated_coil.mp4', writer = 'ffmpeg', fps = 30)
  
# show the plot
plt.show()

2、输出​ ​

此图为动画截图。

3​、代码的部分解释

    现在让我们来逐段分析代码:

fig = plt.figure()
ax = plt.axes(xlim=(-50, 50), ylim=(-50, 50))
line, = ax.plot([], [], lw=2)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    # t is a parameter
    t = 0.1*i


    # x, y values to be plotted
    x = t*np.sin(t)
    y = t*np.cos(t)


    # appending new points to x, y axes points list
    xdata.append(x)
    ydata.append(y)
    
    # set/update the x and y axes data
    line.set_data(xdata, ydata)


    # return line object
    return line,

t = 0.1*i

x = t*np.sin(t)
y = t*np.cos(t)

line.set_data(xdata, ydata)
return line,

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=500, interval=20, blit=True)

它需要下面解释的各种参数:

到此这篇关于Python中的图形绘制简单动画实操的文章就介绍到这了,更多相关Python中的图形绘制动画内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://blog.51cto.com/u_14857544/4913835

标签:[!--infotagslink--]

您可能感兴趣的文章: