SoFunction
Updated on 2024-11-15

How to use Python to create fun GIF animated graphic details

preamble

Previously we shared9 Common Ways to Visualize with Python. In fact, we can also make the visualization of graphical compulsion a little higher, today we share how to make the visualization show: using Python and matplotlib to create GIF charts.

If you do not have ImageMagick installed on your computer, first go to thehere areDownload the corresponding version according to your computer system, you can also download it through me:https:///softs/If we want to use matplotlib's save method to render GIF motion pictures, we need to install ImageMagick.

Below is an example of a motion picture we created:

Two things to note: The scatter in the chart doesn't move, it's the lines that move. The X-axis title changes every frame.

Here is the code we used to create the above GIF image:

import sys
import numpy as np
import  as plt
from  import FuncAnimation

fig, ax = ()
fig.set_tight_layout(True)

# Ask for the size and DPI (dots per inch) of the graphic on the screen
# Note that when saving a graphic as a file, you need to provide a separate DPI for this.
print('fig size: {0} DPI, size in inches {1}'.format(
 fig.get_dpi(), fig.get_size_inches()))

# Draw a scatterplot that stays the same (and is not redrawn) as well as the initial line
x = (0, 20, 0.1)
(x, x + (0, 3.0, len(x)))
line, = (x, x - 5, 'r-', linewidth=2)

def update(i):
 label = 'timestep {0}'.format(i)
 print(label)
# Update lines and axes (with a new X-axis label)
 # Return the objects that need to be redrawn for this frame as a tuple
 line.set_ydata(x - 5 + i)
 ax.set_xlabel(label)
 return line, ax

if __name__ == '__main__':
 # The Update function is called for each frame.
 # Here FunAnimation sets up a 10-frame animation with 200ms intervals between each frame.
 anim = FuncAnimation(fig, update, frames=(0, 10), interval=200)
 if len() > 1 and [1] == 'save':
  ('', dpi=80, writer='imagemagick')
 else:
  # () will always loop the animation
  ()

If you want a cooler theme, you can use the seaborn library, just add it:

import seaborn

Then you get the GIF below:

A little reminder: although we have only 10 frames of GIFs here, and the graphic content is simple, each frame is still about 160k. Since GIF motion graphics don't use cross-frame compression, this makes GIFs with longer frames very large. Minimizing the number of frames and making each frame a little smaller (by resizing the graphic or DPI in matplotlib) can more or less help alleviate this problem.

summarize

Above is the entire content of this article, I hope that the content of this article on your learning or work has a certain reference learning value, if there are questions you can leave a message to exchange, thank you for my support.

References:drawing-animated-gifs-with-matplotlib/