This is the 20th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

Review and

In the matplotlib module we learned how to draw static figures such as broken lines, bars, scatters, histograms, etc. As we all know, there are three script layers in the Matplotlib module to provide users with quick drawing methods. After receiving the commands of the script layer, the artist layer sends the drawing instructions to the back end, and the back end provides drawing operations, event response and graphics rendering. Specific details can be found in previous articles below

  • Matplotlib: Underlying structure of the matplotlib module

  • Matplotlib Line chart Drawing: This section describes the line chart attributes

  • Matplotlib Bar chart drawing: This section describes the attributes of a bar chart

  • Matplotlib: a common drawing method for rectangles and circles

  • Matplotlib Drawing 3D Graphics: Describes how to draw 3D graphics with Mplot3D

In matplotlib module, besides the above static graph drawing, Animation class is also provided to support the production of dynamic graph drawing

Matplotlib. animation Let’s go~

1. Summary of Animation

Animation is the Animation class of the Matplotlib module to produce real-time Animation, including three subclasses

  • Animation is the base class of the Animation class
  • TimedAnimation is a subclass of Animation that draws each frame by drawing time
  • FuncAnimation is based on the Timed subclass, which can draw an animation by repeatedly calling the Fun () method
  • ArtistAnimation uses a set of Artist objects to draw animations

  • Drawing animation features

    • Draw object reference: Animation objects must remain valid for a long time during animation, otherwise they will be recycled by the system and the animation will be paused
    • Animation timer: Is the only reference object to which an animation object is pushed
    • Save animation: Use animation.save, animation.To_html5_video or animation.To_jshtml to save animation
    • Matpoltlib. animation also provides classes for movie formats
  • Animation method

    Matplotlib. Animation. Animation () is the base class animation class, cannot be used. The two commonly used classes are mainly animation and two subclasses

    • matplotlib.animation.FuncAnimation
      matplotlib.animation.FuncAnimation(fig, func, 
      frames=None,
      init_func=None, 
      fargs=None, 
      save_count=None, 
      * , cache_frame_data=True, 
      **kwargs)
      Copy the code
    • matplotlib.animation.ArtistAnimation
      matplotlib.animation.ArtistAnimation(fig, 
      artists,  
      *args,  
      **kwargs)
      Copy the code

2. Draw dynamic diagram steps

The most important thing for matplotlib to draw dynamic graph is to prepare the data displayed in each frame. Generally, FuncAnimation can be used to pass in the FUNC method to generate continuous numbers. Therefore, the main steps for matplotlib to draw dynamic graph are:

  • Import matplotlib.pyplot for drawing graphs and matplotlib.animation for making dynamic graphs
import matplotlib.pyplot as plt
import matplotlib.animation as animation
Copy the code
  • Use the Pyplot. Subplots to create a FIG canvas object and a set of subplots
fig,ax = plt.subplots()
Copy the code
  • Call numpy.random or numpy.arange() to prepare x and y data
x = np.arange(0.2*np.pi, 0.01)
Copy the code
  • Axes objects call plot(), scatter(), hist() and other plotting methods and assign values to list objects
line, = ax.plot(x, np.cos(x),color="pink")
Copy the code
  • You need to define a special update data method to generate the data displayed for each frame, such as func()
def update(i) :
    line.set_ydata(np.cos(x + i / 50))
    return line,
Copy the code
  • Call animation.funcanimation with the FIG and update() methods
ani = animation.FuncAnimation(
    fig, update, interval=20, blit=True, save_count=50)
Copy the code
  • A call to plt.show() shows the dynamic graph
plt.show()
Copy the code
  • We can call animation.save(“movie.gif”,writer=” Pillow “) to save the animation to GIF format

Ps: We need PIP Install Pillow to install the Pillow library in advance, otherwise we will be prompted not to use it


ani.save("movie.gif",writer='pillow')

Copy the code

3. Test the cat

We use the animation class to draw the histogram dynamic graph. Several points need to be paid attention to during the drawing process

  • Use numpy.linspace to generate 100 arithmetic sequences at -5, 5
  • Use numpy.random.randn() to generate random data
  • The Axes object calls hist() to return n,bins,BarContainer
  • Define a recursive update() function that uses the Python closure to trace BarContainer to update the histogram rectangle height each time
  • Call the animation.funcanimation () method to draw the dynamic diagram
def drawanimationhist() :
    fig, ax = plt.subplots()
    BINS = np.linspace(-5.5.100)
    data = np.random.randn(1000)
    n, _ = np.histogram(data, BINS)
    _, _, bar_container = ax.hist(data, BINS, lw=2,
                                  ec="b", fc="pink")
    def update(bar_container) :
        def animate(frame_number) :
            data = np.random.randn(1000)
            n, _ = np.histogram(data, BINS)
            for count, rect in zip(n, bar_container.patches):
                rect.set_height(count)
            return bar_container.patches
        return animate

    ax.set_ylim(top=55)

    ani = animation.FuncAnimation(fig, update(bar_container), 50,
                                  repeat=False, blit=True)
    plt.show()
Copy the code

conclusion

In this issue, we will learn related methods of making animation of matplotlib module. Func methods need to be defined to update the data required for each frame during the process of drawing dynamic diagrams.

That’s the content of this episode. Please give us your thumbs up and comments. See you next time