Python uses matplotlib to draw an animation

Source: Internet
Author: User

Python uses matplotlib to draw an animation

This example describes how to use matplotlib to draw an animation in Python. Share it with you for your reference. The specific analysis is as follows:

Matplotlib supports animation rendering since version 1.1.0.

Below are several examples:

The first example uses generator to run the data_gen function every two seconds:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

#-*-Coding: UTF-8 -*-

Import numpy as np

Import matplotlib. pyplot as plt

Import matplotlib. animation as animation

Fig = plt. figure ()

Axes1 = fig. add_subplot (111)

Line, = axes1.plot (np. random. rand (10 ))

# Because the update parameter calls the data_gen function,

# Therefore, the first default parameter cannot be framenum.

Def update (data ):

Line. set_ydata (data)

Return line,

# Generate 10 random data records at a time

Def data_gen ():

While True:

Yield np. random. rand (10)

Ani = animation. FuncAnimation (fig, update, data_gen, interval = 2*1000)

Plt. show ()

The second example uses list (metric). Each time a row of data from metric is taken as a parameter and sent to update:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Import numpy as np

Import matplotlib. pyplot as plt

Import matplotlib. animation as animation

Start = [1, 0.18, 0.63, 0.29, 0.03, 0.24, 0.86, 0.07, 0.58, 0]

Metric = [[0.03, 0.86, 0.65, 0.34, 0.34, 0.02, 0.22, 0.74, 0.66, 0.65],

[0.43, 0.18, 0.63, 0.29, 0.03, 0.24, 0.86, 0.07, 0.58, 0.55],

[0.66, 0.75, 0.01, 0.94, 0.72, 0.77, 0.20, 0.66, 0.81, 0.52]

]

Fig = plt. figure ()

Window = fig. add_subplot (111)

Line, = window. plot (start)

# If the parameter is list, an element in the list will be retrieved each time by default,

# Metric [0], metric [1],...

Def update (data ):

Line. set_ydata (data)

Return line,

Ani = animation. FuncAnimation (fig, update, metric, interval = 2*1000)

Plt. show ()

Example 3:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

Import numpy as np

From matplotlib import pyplot as plt

From matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate

Fig = plt. figure ()

Ax = plt. axes (xlim = (0, 2), ylim = (-2, 2 ))

Line, = ax. plot ([], [], lw = 2)

# Initialization function: plot the background of each frame

Def init ():

Line. set_data ([], [])

Return line,

# Animation function. This is called sequentially

# Note: I is framenumber

Def animate (I ):

X = np. linspace (0, 2, 1000)

Y = np. sin (2 * np. pi * (x-0.01 * I ))

Line. set_data (x, y)

Return line,

# Call the animator. bmat= True means only re-draw the parts that have changed.

Anim = animation. FuncAnimation (fig, animate, init_func = init,

Frames = 200, interval = 20, BITs = True)

#Anim.save('basic_animation.mp4 ', fps = 30, extra_args = ['-vcodec', 'libx264'])

Plt. show ()

Example 4:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

#-*-Coding: UTF-8 -*-

Import numpy as np

Import matplotlib. pyplot as plt

Import matplotlib. animation as animation

# A new coordinate point is generated each time.

Def data_gen ():

T = data_gen.t

Cnt = 0

While cnt <1000:

Cnt + = 1

T + = 0.05

Yield t, np. sin (2 * np. pi * t) * np. exp (-t/10 .)

Data_gen.t = 0

# Drawing

Fig, ax = plt. subplots ()

Line, = ax. plot ([], [], lw = 2)

Ax. set_ylim (-1.1, 1.1)

Ax. set_xlim (0, 5)

Ax. grid ()

Xdata, ydata = [], []

# Because the run parameter calls the data_gen function,

# So the first parameter may not be framenum: Set line data and return line

Def run (data ):

# Update the data

T, y = data

Xdata. append (t)

Ydata. append (y)

Xmin, xmax = ax. get_xlim ()

If t> = xmax:

Ax. set_xlim (xmin, 2 * xmax)

Ax. figure. canvas. draw ()

Line. set_data (xdata, ydata)

Return line,

# Call the run function every 10 seconds. The run parameter is the data_gen function,

# Indicates that the image only updates the elements to be drawn.

Ani = animation. FuncAnimation (fig, run, data_gen, bgen = True, interval = 10,

Repeat = False)

Plt. show ()

Let's look at the following example:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

#-*-Coding: UTF-8 -*-

Import numpy as np

Import matplotlib. pyplot as plt

Import matplotlib. animation as animation

# The first parameter must be framenum.

Def update_line (num, data, line ):

Line. set_data (data [...,: num])

Return line,

Fig1 = plt. figure ()

Data = np. random. rand (2, 15)

L, = plt. plot ([], [], 'r -')

Plt. xlim (0, 1)

Plt. ylim (0, 1)

Plt. xlabel ('x ')

Plt. title ('test ')

# After framenum is increased from 1 to 25, the returned value is increased from 1 to 25 again. Then, the returned value is...

Line_ani = animation. FuncAnimation (fig1, update_line, 25, fargs = (data, l), interval = 50, bval = True)

# Equivalent

# Line_ani = animation. FuncAnimation (fig1, update_line, frames = 25, fargs = (data, l ),

# Interval = 50, bval = True)

# Ignore the frames parameter. framenum will be added from 1 until it is infinite.

# Since data does not change after the frame reaches 25, you will find that the image does not change after the frame reaches 25.

# Line_ani = animation. FuncAnimation (fig1, update_line, fargs = (data, l ),

# Interval = 50, bval = True)

Plt. show ()

I hope this article will help you with python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.