使用Matplotlib繪製3D動畫

使用Matplotlib繪製3D動圖

主角是FuncAnimation函數,通過不斷地調用func函數來實現動畫,還可以使用save(filename, writer=None, fps=None, dpi=None, codec=None, bitrate=None, extra_args=None, metadata=None, extra_anim=None, savefig_kwargs=None)來保存動畫,下面我們主要講下FuncAnimation函數的使用

matplotlib.animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, **kwargs)

官方文檔

主要參數

  • fig: matplotlib.figure.Figure

    用來畫圖、變化尺寸或者其他需要的事件的figure對象

  • func: callable

    每一幀調用的函數。

     def func(frame, *fargs) -> iterable_of_artists:

    第一個參數是下一幀的值,任何額外的參數都可以通過fargs參數得到

  • frames: iterable, int, generator function, or None, optional

    用來傳遞函數和動畫的每一幀的數據源,控制幀的迭代

  • init_func : callable, optional

    用來畫初始幀的函數,這個函數只會在第一幀之前被調用一次。如果沒有給出的話,那麼幀序列中的第一幀將會用來替代。
    If blit == True, init_func必須返回可迭代形式

  • fargs: tuple or None, optional

    傳遞給每一次func調用的額外的參數

  • save_count: int,optional

    從幀到緩存的值的數量

  • interval : number, optional

    幀間距(單位ms),默認200毫秒

  • repeat_delay : number, optional

    動畫循環間距,默認None

  • repeat : bool, optional

    動畫是否要循環播放,默認爲True

  • blit : bool, optional

    控制是否使用blitting來優化繪圖

官方示例

"""
============
3D animation
============

A simple example of an animated plot... In 3D!
"""
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation


def Gen_RandLine(length, dims=2):
    """
    Create a line using a random walk algorithm

    length is the number of points for the line.
    dims is the number of dimensions the line has.
    """
    lineData = np.empty((dims, length))
    lineData[:, 0] = np.random.rand(dims)   # 初始化起點
    for index in range(1, length):
        # scaling the random numbers by 0.1 so
        # movement is small compared to position.
        # subtraction by 0.5 is to change the range to [-0.5, 0.5]
        # to allow a line to move backwards.
        step = ((np.random.rand(dims) - 0.5) * 0.1)  # 步長
        # 下一步的位置
        lineData[:, index] = lineData[:, index - 1] + step

    return lineData   # 返回一個shape爲(3,25)的數組,3維座標25幀


def update_lines(num, dataLines, lines):
    for line, data in zip(lines, dataLines):
        # NOTE: there is no .set_data() for 3 dim data...
        line.set_data(data[0:2, :num])
        line.set_3d_properties(data[2, :num])
    return lines

# Attaching 3D axis to the figure
fig = plt.figure()
ax = p3.Axes3D(fig)

# Fifty lines of random 3-D lines  (長爲50的數組,每個元素爲shape爲3,25的ndarray,最後實際效果就是50條路徑)
data = [Gen_RandLine(25, 3) for index in range(50)]

# Creating fifty line objects.
# NOTE: Can't pass empty arrays into 3d version of plot()
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data] # 每條路徑的起始點

# Setting the axes properties
ax.set_xlim3d([0.0, 1.0])
ax.set_xlabel('X')

ax.set_ylim3d([0.0, 1.0])
ax.set_ylabel('Y')

ax.set_zlim3d([0.0, 1.0])
ax.set_zlabel('Z')

ax.set_title('3D Test')

# Creating the Animation object
line_ani = animation.FuncAnimation(fig, update_lines, 25, fargs=(data, lines),
                                   interval=50, blit=False)

plt.show()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章