logo

Trazado de gráficos en Python | Conjunto 3

Trazado de gráficos en Python | Conjunto 1 Trazado de gráficos en Python | Conjunto 2 Matplotlib es una biblioteca bastante extensa que admite animaciones de gráficos también. Las herramientas de animación se centran en el matplotlib.animación Clase base que proporciona un marco alrededor del cual se construye la funcionalidad de animación. Las principales interfaces son Animación cronometrada y FuncAnimación y de los dos FuncAnimación es el más conveniente de usar. Instalación:
    Matplotlib: Consulte Trazado de gráficos en Python | Conjunto 1 Numerosos: You can install numpy module using following pip command:
    pip install numpy
    FFMPEG: Sólo es necesario para guardar la animación como vídeo. El ejecutable se puede descargar desde aquí .
Implementación: 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 hacha que actúa como subtrama. El rango/límite para los ejes x e y también se definen al crear el elemento de ejes. Finalmente creamos el trama elemento nombrado como línea . Inicialmente, los puntos de los ejes x e y se definieron como listas vacías y anchos de línea. (lw) se ha fijado en 2.
  • def init(): line.set_data([] []) return line
    Now we declare a initialization function calor . El animador llama a esta función para 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() El animador llama una y otra vez a la función para crear cada fotograma. El número de veces que se llamará a esta función está determinado por el número de fotogramas que se pasa como marcos Argumento al 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 establecer_datos() función para establecer datos x e y y luego devolver el objeto de trazado línea .
  • anim = animation.FuncAnimation(fig animate init_func=init frames=500 interval=20 blit=True)
    Now we create the FuncAnimation object seis . Se necesitan varios argumentos que se explican a continuación: higo : figura a trazar. animar : la función que se llamará repetidamente para cada cuadro . función_init : función utilizada para dibujar un marco claro. Se llama una vez antes del primer cuadro. marcos : número de fotogramas. (Nota: marcos también puede ser un iterable o un generador). intervalo : duración entre fotogramas (en milisegundos) permanecer : configurar blit=True significa que solo se dibujarán aquellas partes que hayan cambiado.
  • anim.save('animated_coil.mp4' writer = 'ffmpeg' fps = 30)
    Now we save the animator object as a video file using ahorrar() función. Necesitará un escritor de películas para guardar el video de animación. En este ejemplo hemos utilizado el escritor de películas FFMPEG. Entonces escritor está configurado como 'ffmpeg'. fps significa fotograma por segundo.
Ejemplo 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 de estrella se obtiene poniendo k = 2,5 y 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)
Considerándolo todo, las animaciones son una gran herramienta para crear cosas increíbles y se pueden crear muchas más cosas usándolas. Así es como se pueden generar y guardar gráficos animados usando Matplotlib. Crear cuestionario