logo

Изчертаване на графики в Python | Комплект 3

Изчертаване на графики в Python | Комплект 1 Изчертаване на графики в Python | Комплект 2 Matplotlib е доста обширна библиотека, която поддържа Анимации на графиките също. Инструментите за анимация са центрирани около matplotlib.animation базов клас, който осигурява рамка, около която е изградена функционалността на анимацията. Основните интерфейси са TimedAnimation и FuncAnimation и от двете FuncAnimation е най-удобният за използване. Инсталация:
    Matplotlib: Обърнете се към Изчертаване на графики в Python | Комплект 1 Numpy: You can install numpy module using following pip command:
    pip install numpy
    FFMPEG: Изисква се само за запазване на анимацията като видео. Изпълнимият файл може да бъде изтеглен от тук .
Изпълнение: 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 брадва който действа като подзаговор. Диапазонът/лимитът за оста x и y също се определят при създаването на елемента оси. Накрая създаваме парцел елемент, наречен като линия . Първоначално точките на оста x и y са дефинирани като празни списъци и ширина на линията (lw) е определен като 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 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() функция за задаване на x и y данни и след това връщане на графика линия .
  • anim = animation.FuncAnimation(fig animate init_func=init frames=500 interval=20 blit=True)
    Now we create the FuncAnimation object шест . Необходими са различни аргументи, обяснени по-долу: фиг : фигура за начертаване. оживявам : функцията, която трябва да се извиква многократно за всеки кадър . init_func : функция, използвана за изчертаване на ясна рамка. Извиква се веднъж преди първия кадър. рамки : брой кадри. (Забележка: рамки може също да бъде итерируем или генератор.) интервал : продължителност между кадрите (в милисекунди) остани : настройка blit=True означава, че ще бъдат изчертани само онези части, които са променени.
  • anim.save('animated_coil.mp4' writer = 'ffmpeg' fps = 30)
    Now we save the animator object as a video file using запази () функция. Ще ви е необходим сценарист на филми, за да запазите анимационния видеоклип. В този пример използвахме FFMPEG сценарист на филми. И така писател е зададено като „ffmpeg“. fps означава рамка в секунда.
Пример 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.
  • Формата на звездата се получава чрез поставяне на k = 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)
Като цяло анимациите са чудесен инструмент за създаване на невероятни неща и много повече неща могат да бъдат създадени с тях. Ето как могат да се генерират и записват анимирани графики с помощта на Matplotlib. Създаване на тест