Как оживить фигуры в сюжетах? - PullRequest
0 голосов
/ 04 сентября 2018

Я написал код для объяснения суперпозиции волн. Я вставляю свои код и выходные данные ниже. Но проблема в том, что я просто создаю статический график ... Все становится более интересным, если я могу анимировать волны (в моем коде: subplot(211)), и результат коррекции получается в subplot(212). Но до сих пор я могу только анимировать без сюжетов ... и когда я исследовал в интернете "анимацию на сюжетах с использованием matplotlib", результаты, которые я нашел, не были мне понятны и в этом случае также отличались от моего кода.

Может ли кто-нибудь помочь мне в этом отношении? Было бы лучше, если бы анимация основывалась на моей следующей структуре кода (разумеется, необходимо внести необходимые изменения в анимацию субплота). Спасибо всем.

Мой код

#Composition of Waves
import matplotlib as mpl
mpl.rc('text', usetex = True)
mpl.rc('font', family = 'serif')
import matplotlib.pyplot as plt
import numpy as np

plt.gca().set_aspect('equal', adjustable='box')
plt.style.use(['ggplot','dark_background'])

title = 'Composition of Waves'
#Parameters:
#a=Amplitude; w=Angular Frequency; phi = Phase Angle.

#Definition of the function:
def f(t,a,w,phi): 
    y = a*np.sin(w*t + phi)
    return y

t = np.arange(0,4*np.pi,0.001)

def create_plot(ptype):
    y1 = f(t,1,1,1)
    y2 = f(t,2,2,2)
    y = y1 + y2
    if ptype == 'waves':
        plt.plot(t, y1, label='$y=f_1(t)$')
        plt.plot(t, y2, label='$y=f_2(t)$')
    elif ptype == 'composition':
        plt.plot(t, y, label='$Composition$', color= 'm')

plt.figure(1)
plt.subplot(211)                                  
create_plot('waves')
plt.legend()
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
#plt.xlabel('$x$')
plt.ylabel('$y$')
plt.title(title)

plt.subplot(212)
create_plot('composition')
plt.legend()
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.xlabel('$t$')
plt.ylabel('$y$')

# Tweak spacing between subplots to prevent labels 
from overlapping
plt.subplots_adjust(hspace=0.5)

plt.savefig('composition_Waves.eps', format='eps', dpi=1000,bbox_inches='tight')

plt.show()

выход Code Output

Здесь я хочу анимировать волны в различных w и phi.

1 Ответ

0 голосов
/ 04 сентября 2018

Создание анимации не отличается от того, есть ли у вас сюжеты или нет. Единственное, что имеет значение, - это сохранить ссылку на ваши Artist объекты (в этом случае Line2D объекты, возвращаемые plt.plot(), чтобы иметь возможность изменять свои свойства (данные) в функции анимации.

import matplotlib as mpl
mpl.rc('text', usetex = False)
mpl.rc('font', family = 'serif')
import matplotlib.pyplot as plt
import numpy as np

plt.gca().set_aspect('equal', adjustable='box')
plt.style.use(['ggplot','dark_background'])

title = 'Composition of Waves'
#Parameters:
#a=Amplitude; w=Angular Frequency; phi = Phase Angle.

#Definition of the function:
def f(t,a,w,phi): 
    y = a*np.sin(w*t + phi)
    return y

t = np.arange(0,4*np.pi,0.001)

def create_plot(ptype):
    y1 = f(t,1,1,1)
    y2 = f(t,2,2,2)
    y = y1 + y2
    arts = []
    if ptype == 'waves':
        l1, = plt.plot(t, y1, label='$y=f_1(t)$')
        l2, = plt.plot(t, y2, label='$y=f_2(t)$')
        arts = [l1, l2]
    elif ptype == 'composition':
        l3, = plt.plot(t, y, label='$Composition$', color= 'm')
        arts = [l3]
    return arts ## return the artists created by `plt.plot()`



my_lines = [] ## array to keep track of the Line2D artists
fig = plt.figure(1)
plt.subplot(211)                                  
l = create_plot('waves') 
my_lines += l ## add artists to array
plt.legend()
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
#plt.xlabel('$x$')
plt.ylabel('$y$')
plt.title(title)

plt.subplot(212)
l = create_plot('composition')
my_lines += l
plt.legend()
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.xlabel('$t$')
plt.ylabel('$y$')

# Tweak spacing between subplots to prevent labels from overlapping
plt.subplots_adjust(hspace=0.5)

print(my_lines)

def animate(i):
    ## in this examples, i takes values 0-10 by steps of 0.01 (the frames in the animation call)
    ## and will represent the frequency of the 2nd wave in the top subplot
    y1 = f(t,1,1,1)
    y2 = f(t,2,i,2)
    y = y1 + y2

    # update the content of the Line2D objects
    my_lines[1].set_ydata(y2)
    my_lines[2].set_ydata(y)
    return my_lines ## return updated artists

ani = animation.FuncAnimation(fig, animate, frames=np.linspace(0,10,100))

plt.show()

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...