Как оживить сложную функцию с помощью matplotlib? - PullRequest
0 голосов
/ 08 июля 2020

Я хочу сделать анимацию с функцией ((phi^n)-((-1/phi)^n))/(5^0.5) (формула B inet) как n ∈ ℝ, чтобы график начинался как прямая линия на реальных осях, а затем переходил в фактический график. Я попытался добавить

from matplotlib.animation import FuncAnimation
.
.
.
    def g(val):
        main_graph.set_ydata(imag(f(x))*val)
        return main_graph,
    animation = FuncAnimation(main_graph, func=g, frames=arange(0, 10, 0.1), interval=10)
plt.show

Однако это не сработало, и я понятия не имею, почему я следил за различными руководствами, и все они имели одинаковый результат (ошибка). Я также пробовал

import matplotlib.animation as animation
.
.
.
def init():
    main_graph.set_ydata([np.nan] * len(real(f(x))))
    return main_graph,
def g(val):
    main_graph.set_ydata(imag(f(x))*val)
    return main_graph,
ani = animation.FuncAnimation(main_graph, g, init_func=init, interval=2, blit=True, save_count=50)

Ошибка в обоих случаях: AttributeError: 'Line2D' object has no attribute 'canvas'. Вот полный код

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from numpy import arange, real, imag
phi = (1+(5**0.5))/2
x = arange(0,5,0.01)
def f(x):
    return ((phi**(x+0j))-((-1/phi)**(x+0j)))/(5**0.5)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position(('data', 0.0))
ax.spines['bottom'].set_position(('data', 0))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
#labels for x and y axes
plt.xlabel('real')
plt.ylabel('imag')
plt.grid(alpha=.4,linestyle=':')
main_graph, = plt.plot(real(f(x)),imag(f(x)), label='((phi**(x+0j))-((-1/phi)**(x+0j)))/(5**0.5)')
plt.legend()
    def g(val):
        main_graph.set_ydata(imag(f(x))*val)
        return main_graph,
    animation = FuncAnimation(main_graph, func=g, frames=arange(0, 10, 0.1), interval=10)
plt.show()

Чтобы увидеть окончательный график, используйте этот код

import matplotlib.pyplot as plt
from numpy import arange, real, imag
phi = (1+(5**0.5))/2
x = arange(0,5,0.01)
def f(x):
    return ((phi**(x+0j))-((-1/phi)**(x+0j)))/(5**0.5)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position(('data', 0.0))
ax.spines['bottom'].set_position(('data', 0))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
#labels for x and y axes
plt.xlabel('real')
plt.ylabel('imag')
plt.grid(alpha=.4,linestyle=':')
main_graph, = plt.plot(real(f(x)),imag(f(x)), label='((phi**(x+0j))-((-1/phi)**(x+0j)))/(5**0.5)')
plt.legend()
plt.show()

1 Ответ

0 голосов
/ 08 июля 2020

Я адаптировал пример из документации анимации matplotlib . Вот как был изменен код, чтобы разрешить изменение элементов оси (в данном случае легенды), установив blit=False

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from numpy import arange, real, imag
phi = (1+(5**0.5))/2
x = arange(0,5,0.01)
def f(x):
    return ((phi**(x+0j))-((-1/phi)**(x+0j)))/(5**0.5)
fig = plt.figure()
main_graph, = plt.plot(real(f(x)),imag(f(x)), label='((phi**(x+0j))-((-1/phi)**(x+0j)))/(5**0.5)')
#labels for x and y axes
plt.xlabel('real')
plt.ylabel('imag')
plt.grid(alpha=.4,linestyle=':')
#plt.legend(loc=4)

def init():
    global legs
    ax = fig.add_subplot(1, 1, 1)
    ax.spines['left'].set_position(('data', 0.0))
    ax.spines['bottom'].set_position(('data', 0))
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.set_ylim(-4,4)
    legs=ax.legend(loc=4, prop={'size': 12})
    return main_graph, 
    
def g(val):
    main_graph.set_ydata(imag(f(x))*val)
    label = '((phi**(x+0j))-((-1/phi)**(x+0j)))/(5**0.5)x{}'.format(val)
    legs.texts[0].set_text(label)
    return main_graph, 
#Note that blit has been set to False, because axes elements are being modified
animation = FuncAnimation(fig, func=g,frames=arange(0, 10, 0.1), init_func=init,interval=10,blit=False)
animation.save('animation.gif', writer='imagemagick', fps=30)
plt.show()

Вот как выглядит анимация: анимация

...