logo

Plotagem de gráficos em Python | Conjunto 3

Plotagem de gráficos em Python | Conjunto 1 Plotagem de gráficos em Python | Conjunto 2 Matplotlib é uma biblioteca bastante extensa que suporta Animações de gráficos também. As ferramentas de animação giram em torno do matplotlib.animation classe base que fornece uma estrutura em torno da qual a funcionalidade de animação é construída. As principais interfaces são Animação cronometrada e FuncAnimação e dos dois FuncAnimação é o mais conveniente de usar. Instalação:
    Matplotlib: Consulte Plotagem de gráficos em Python | Conjunto 1 Entorpecido: You can install numpy module using following pip command:
    pip install numpy
    FFMPEG: É necessário apenas para salvar a animação como vídeo. O executável pode ser baixado em aqui .
Implementação: 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 machado que funciona como uma subtrama. O intervalo/limite para os eixos xey também são definidos durante a criação do elemento de eixos. Finalmente criamos o trama elemento nomeado como linha . Inicialmente, os pontos dos eixos xey foram definidos como listas vazias e largura de linha (lw) foi definido como 2.
  • def init(): line.set_data([] []) return line
    Now we declare a initialization function aquecer . Esta função é chamada pelo animador para criar o primeiro quadro.
  • 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() A função é chamada repetidamente pelo animador para criar cada quadro. O número de vezes que esta função será chamada é determinado pelo número de quadros que são passados ​​como quadros argumento para o 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_dados() função para definir os dados x e y e depois retornar o objeto do gráfico linha .
  • anim = animation.FuncAnimation(fig animate init_func=init frames=500 interval=20 blit=True)
    Now we create the FuncAnimation object seis . São necessários vários argumentos explicados abaixo: Figo : figura a ser plotada. animar : a função a ser chamada repetidamente para cada quadro . função_inicial : função usada para desenhar um quadro claro. É chamado uma vez antes do primeiro quadro. quadros : número de quadros. (Observação: quadros também pode ser um iterável ou gerador.) intervalo : duração entre frames (em milissegundos) ficar : definir blit=True significa que apenas serão desenhadas as partes que foram alteradas.
  • anim.save('animated_coil.mp4' writer = 'ffmpeg' fps = 30)
    Now we save the animator object as a video file using salvar() função. Você precisará de um roteirista para salvar o vídeo de animação. Neste exemplo, usamos o gravador de filmes FFMPEG. Então escritor está definido como 'ffmpeg'. FPS significa quadro por segundo.
Exemplo 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.
  • A forma de estrela é obtida colocando k = 2,5 e 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)
Resumindo, as animações são uma ótima ferramenta para criar coisas incríveis e muito mais coisas podem ser criadas usando-as. Então foi assim que gráficos animados podem ser gerados e salvos usando Matplotlib. Criar questionário