logo

Исцртавање графикона у Питхон-у | Сет 3

Исцртавање графикона у Питхон-у | Сет 1 Исцртавање графикона у Питхон-у | Сет 2 Матплотлиб је прилично опсежна библиотека која подржава Анимације графова такође. Алатке за анимацију се усредсређују око матплотлиб.аниматион базна класа која обезбеђује оквир око којег се гради функционалност анимације. Главни интерфејси су ТимедАниматион и ФунцАниматион а од два ФунцАниматион је најпогоднији за употребу. Инсталација:
    Матплотлиб: Погледајте Исцртавање графикона у Питхон-у | Сет 1 Нумпи: You can install numpy module using following pip command:
    pip install numpy
    ФФМПЕГ: Потребно је само за чување анимације као видео записа. Извршни фајл се може преузети са овде .
Имплементација: 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 ак који делује као подзаплет. Опсег/ограничење за к и и оси су такође дефинисани током креирања елемента оса. Коначно креирамо плот елемент назван као линија . У почетку су тачке осе к и и дефинисане као празне листе и ширина линије (лв) постављено је као 2.
  • def init(): line.set_data([] []) return line
    Now we declare a initialization 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
    This is the most important function of above program. анимирати() функцију позива аниматор изнова и изнова да би направио сваки кадар. Број пута које ће ова функција бити позвана је одређен бројем оквира који се прослеђује као рамови аргумент аниматору. анимирати() 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 т 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 сет_дата() функција за постављање података к и и, а затим враћање објекта плот линија .
  • anim = animation.FuncAnimation(fig animate init_func=init frames=500 interval=20 blit=True)
    Now we create the FuncAnimation object шест . Потребни су различити аргументи објашњени у наставку: сл : фигура која се исцртава. анимирати : функција која се позива више пута за сваки оквир . инит_фунц : функција која се користи за цртање јасног оквира. Позива се једном пре првог кадра. рамови : број оквира. (Напомена: рамови такође може бити итерабле или генератор.) интервал : трајање између кадрова (у милисекундама) остати : сеттинг блит=Труе значи да ће бити нацртани само они делови који су промењени.
  • anim.save('animated_coil.mp4' writer = 'ffmpeg' fps = 30)
    Now we save the animator object as a video file using сачувај() функција. Биће вам потребан писац филмова да бисте сачували анимацијски видео. У овом примеру смо користили ФФМПЕГ филмски писац. Дакле писац је постављен као 'ффмпег'. фпс означава оквир у секунди.
Пример 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.
  • Облик звезде се добија стављањем к = 2,5 и 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)
Све у свему, анимације су одличан алат за креирање невероватних ствари и много више ствари се може креирати помоћу њих. Тако се анимирани цртежи могу генерисати и сачувати помоћу Матплотлиб-а. Креирај квиз