日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python中的圖形繪制簡單動畫實操_python

作者:來西瓜 ? 更新時間: 2022-04-25 編程語言

前言:

? ? ? 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)
  • ?? ?1)首先創建一個圖形,即所有子圖的頂級容器。
  • ?? ?2)然后創建一個軸元素 ax 作為子圖。 在創建軸元素時還定義了 x 和 y 軸的范圍/限制。
  • ?? ?3)最后,創建名為 line, 的 plot 元素。 最初,x 和 y 軸點已定義為空列表,線寬 (lw) 已設置為 2。
def init():
? ? line.set_data([], [])
? ? return line,
  • ?? ?4)聲明一個初始化函數 init 。 動畫師調用此函數來創建第一幀。
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,
  • ?? ?5)這是上述程序最重要的功能。animate() 函數被動畫師一次又一次地調用來創建每一幀。 調用此函數的次數由幀數決定,該幀數作為幀參數傳遞給動畫師。
  • ?? ?6)animate() 函數以第 i 個幀的索引作為參數。
t = 0.1*i
  • ?? ?7)我們巧妙地使用了當前幀的索引作為參數!
x = t*np.sin(t)
y = t*np.cos(t)
  • ?? ?8)由于有了參數 t,可以輕松地繪制任何參數方程。 例如,使用參數方程繪制螺旋線。
line.set_data(xdata, ydata)
return line,
  • ?? ?9)使用set_data() 函數設置 x 和 y 數據,然后返回繪圖對象 line, 。
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=500, interval=20, blit=True)

  • ?? ?10)創建 FuncAnimation 對象 anim

它需要下面解釋的各種參數:

  • ?? ?fig:要繪制的圖形。
  • ?? ?animate:為每一幀重復調用的函數。
  • ?? ?init_func:函數用于繪制清晰的框架。它在第一幀之前被調用一次。
  • ?? ?frames:幀數。
  • ?? ?interval:幀之間的持續時間。
  • ?? ?blit:設置 blit=True 意味著只會繪制那些已經改變的部分。

原文鏈接:https://blog.51cto.com/u_14857544/4913835

欄目分類
最近更新