logo

Traçat gràfic en Python | Set 3

Traçat gràfic en Python | Set 1 Traçat gràfic en Python | Set 2 Matplotlib és una biblioteca força extensa que admet Animacions també de gràfics. Les eines d'animació se centren al voltant de matplotlib.animation classe base que proporciona un marc al voltant del qual es construeix la funcionalitat d'animació. Les principals interfícies són TimedAnimation i FuncAnimation i fora dels dos FuncAnimation és el més còmode d'utilitzar. Instal·lació:
    Matplotlib: Consulteu Traçat gràfic en Python | Set 1 Numpy: You can install numpy module using following pip command:
    pip install numpy
    FFMPEG: només és necessari per desar l'animació com a vídeo. L'executable es pot descarregar des de aquí .
Implementació: Python
# importing required modules import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np # create a figure axis and plot element fig = plt.figure() ax = plt.axes(xlim=(-50 50) ylim=(-50 50)) line = ax.plot([] [] lw=2) # initialization function def init(): # creating an empty plot/frame line.set_data([] []) return line # lists to store x and y axis points xdata ydata = [] [] # animation function def animate(i): # t is a parameter t = 0.1*i # x y values to be plotted x = t*np.sin(t) y = t*np.cos(t) # appending new points to x y axes points list xdata.append(x) ydata.append(y) # set/update the x and y axes data line.set_data(xdata ydata) # return line object return line # setting a title for the plot plt.title('A growing coil!') # hiding the axis details plt.axis('off') # call the animator  anim = animation.FuncAnimation(fig animate init_func=init frames=500 interval=20 blit=True) # save the animation as mp4 video file anim.save('animated_coil.mp4' writer = 'ffmpeg' fps = 30) # show the plot plt.show() 
Here is how the output animation looks like: Now let us try to understand the code in pieces:
  • fig = plt.figure() ax = plt.axes(xlim=(-50 50) ylim=(-50 50)) line = ax.plot([] [] lw=2)
    Here we first create a figure i.e a top level container for all our subplots. Then we create an axes element destral que actua com a subtrama. El rang/límit per als eixos x i y també es defineix mentre es crea l'element dels eixos. Finalment creem el trama element anomenat com línia . Inicialment, els punts de l'eix x i y s'han definit com a llistes buides i ample de línia (lw) s'ha establert com a 2.
  • def init(): line.set_data([] []) return line
    Now we declare a initialization function calor . L'animador crida aquesta funció per crear el primer fotograma.
  • def animate(i): # t is a parameter t = 0.1*i # x y values to be plotted x = t*np.sin(t) y = t*np.cos(t) # appending new points to x y axes points list xdata.append(x) ydata.append(y) # set/update the x and y axes data line.set_data(xdata ydata) # return line object return line
    This is the most important function of above program. animar () La funció és cridada una i altra vegada per l'animador per crear cada fotograma. El nombre de vegades que es cridarà aquesta funció està determinat pel nombre de fotogrames que es transmeten marcs argument a l'animador. animar () function takes the index of ith frame as argument.
    t = 0.1*i
    Here we cleverly use the index of current frame as a parameter!
    x = t*np.sin(t) y = t*np.cos(t)
    Now since we have the parameter t we can easily plot any parametric equation. For example here we are plotting a spiral using its parametric equation.
    line.set_data(xdata ydata) return line
    Finally we use set_data() funció per establir les dades x i y i després retornar l'objecte de traçat línia .
  • anim = animation.FuncAnimation(fig animate init_func=init frames=500 interval=20 blit=True)
    Now we create the FuncAnimation object sis . Pren diversos arguments que s'expliquen a continuació: fig : figura a representar. animar : la funció a cridar repetidament per a cada fotograma . init_func : funció utilitzada per dibuixar un marc clar. Es diu una vegada abans del primer fotograma. marcs : nombre de fotogrames. (Nota: marcs també pot ser un iterable o un generador.) interval : durada entre fotogrames (en mil·lisegons) quedar-se : establir blit=True significa que només es dibuixaran les parts que hagin canviat.
  • anim.save('animated_coil.mp4' writer = 'ffmpeg' fps = 30)
    Now we save the animator object as a video file using desa () funció. Necessitareu un guionista de pel·lícules per desar el vídeo d'animació. En aquest exemple hem utilitzat l'escriptor de pel·lícules FFMPEG. Així que escriptor s'estableix com a "ffmpeg". fps representa fotograma per segon.
Exemple 2 This example shows how one can make a rotating curve by applying some simple mathematics! Python
# importing required modules import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np # create a figure axis and plot element fig = plt.figure() ax = plt.axes(xlim=(-25 25) ylim=(-25 25)) line = ax.plot([] [] lw=2) # initialization function def init(): # creating an empty plot/frame line.set_data([] []) return line # set of points for a star (could be any curve) p = np.arange(0 4*np.pi 0.1) x = 12*np.cos(p) + 8*np.cos(1.5*p) y = 12*np.sin(p) - 8*np.sin(1.5*p) # animation function def animate(i): # t is a parameter t = 0.1*i # x y values to be plotted X = x*np.cos(t) - y*np.sin(t) Y = y*np.cos(t) + x*np.sin(t) # set/update the x and y axes data line.set_data(X Y) # return line object return line # setting a title for the plot plt.title('A rotating star!') # hiding the axis details plt.axis('off') # call the animator  anim = animation.FuncAnimation(fig animate init_func=init frames=100 interval=100 blit=True) # save the animation as mp4 video file anim.save('basic_animation.mp4' writer = 'ffmpeg' fps = 10) # show the plot plt.show() 
Here is how the output of above program looks like: Here we have used some simple mathematics to rotate a given curve.
  • La forma d'estrella s'obté posant k = 2,5 i 0p = np.arange(0 4*np.pi 0.1) x = 12*np.cos(p) + 8*np.cos(1.5*p) y = 12*np.sin(p) - 8*np.sin(1.5*p)
  • Now in each frame we rotate the star curve using concept of rotation in complex numbers. Let x y be two ordinates. Then after rotation by angle theta the new ordinates are: {x}' = xcos theta - ysin theta {y}' = xsin theta + ycos theta The same has been applied here:
    X = x*np.cos(t) - y*np.sin(t) Y = y*np.cos(t) + x*np.sin(t)
Tot plegat, les animacions són una gran eina per crear coses sorprenents i es poden crear moltes més coses utilitzant-les. Així és com es poden generar i desar trames animades mitjançant Matplotlib. Crea un qüestionari