Create plot animation with Python + Matplotlib

code

import numpy
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import mpl_toolkits.mplot3d.axes3d as p3

def plot_3D_animation(X, Y, Z, n_frame=None,
                      xlim=None, ylim=None, zlim=None,
                      step=None, saveanime=None, show=True):
    """3D plotting animation"""
    fig = plt.figure()
    ax = p3.Axes3D(fig)

    if step is None:
        step = 1
    X = X[range(0, len(X), step)]
    Y = Y[range(0, len(Y), step)]
    Z = Z[range(0, len(Z), step)]

    data = [numpy.vstack((X, Y, Z))]

    lines = [ax.plot(dat[0, 0:1], dat[1, 0:1],
                     dat[2, 0:1])[0] for dat in data]

    # Setting the axes properties
    if xlim is None:
        ax.set_xlim3d([X.min(), X.max()])
    elif len(xlim) == 2:
        ax.set_xlim3d(xlim)
    ax.set_xlabel('X')
    if ylim is None:
        ax.set_ylim3d([Y.min(), Y.max()])
    elif len(ylim) == 2:
        ax.set_ylim3d(ylim)
    ax.set_ylabel('Y')
    if zlim is None:
        ax.set_zlim3d([Z.min(), Z.max()])
    elif len(zlim) == 2:
        ax.set_zlim3d(zlim)
    ax.set_zlabel('Z')
    ax.set_title('3D animation')
    ax.view_init(-10, 30)

    def update_lines(num, dataLines, lines):
        for line, data in zip(lines, dataLines):
            line.set_data(data[0:2, :num])
            line.set_3d_properties(data[2,:num])
        return lines

    if n_frame is None:
        n_frame = len(X)

    # Creating the Animation object
    anim = animation.FuncAnimation(fig,
                                   update_lines,
                                   n_frame,
                                   fargs=(data, lines),
                                   interval=1,
                                   blit=False)

    if type(saveanime) == str:
        writer = animation.FFMpegWriter()
        anim.save(saveanime, writer=writer)

    if show is True:
        plt.show()

    plt.clf()
    plt.close()

How to use

>>> import numpy as np
>>> X, Y, Z = np.array([1,2,3]), np.array([2,3,4]), np.array([4,5,6])
>>> plot_3D_animation(X, Y, Z)

Example of use

Recommended Posts

Create plot animation with Python + Matplotlib
Create 3D scatter plot with SciPy + matplotlib (Python)
Animation with matplotlib
Animation with matplotlib
Lognormal probability plot with Python, matplotlib
2-axis plot with Matplotlib
Heatmap with Python + matplotlib
3D plot with matplotlib
Create 3d gif with python3
Stackable bar plot with matplotlib
Create a directory with python
[Python] How to create a 2D histogram with Matplotlib
[Python] How to draw a scatter plot with Matplotlib
A python graphing manual with Matplotlib.
Create Awaitable with Python / C API
[Python] font family and font with matplotlib
Create folders from '01' to '12' with python
Let's create a PRML diagram with Python, Numpy and matplotlib.
Create a virtual environment with Python!
Create an Excel file with Python3
Heatmap with Dendrogram in Python + matplotlib
Continuously color with matplotlib scatter plot
Draw Lyapunov Fractal with Python, matplotlib
When matplotlib doesn't work with python2.7
Easy animation with matplotlib (mp4, gif)
Create a Python function decorator with Class
[Python] Set the graph range with matplotlib
Automatically create Python API documentation with Sphinx
Create wordcloud from your tweet with python3
Build a blockchain with Python ① Create a class
Create a dummy image with Python + PIL.
[Python] Create a virtual environment with Anaconda
Let's create a free group with Python
Quickly create an excel file with Python #python
Create Python + uWSGI + Nginx environment with Docker
Create and decrypt Caesar cipher with python
Create miscellaneous Photoshop videos with Python + OpenCV ③ Create miscellaneous Photoshop videos
[Python] Let's make matplotlib compatible with Japanese
Create Excel file with Python + similarity matrix
Create a word frequency counter with Python 3.4
[Python] Quickly create an API with Flask
Create an English word app with python
Create a graph with borders removed with matplotlib
FizzBuzz with Python3
Scraping with Python
[Python] Violin Plot
Statistics with python
Scraping with Python
Python with Go
#Python basics (#matplotlib)
Twilio with Python
Integrate with Python
Play with 2016-Python
AES256 with python
Tested with Python
python starts with ()
with syntax (Python)
My matplotlib (python)
Japanese with matplotlib
Plot CSV of time series data with unixtime value in Python (matplotlib)
Bingo with python