Встраивание анимированного графика Matplotlib в Tkinter

#python #matplotlib #matplotlib-animation

#python #matplotlib #matplotlib-анимация

Вопрос:

Я создаю программу для моделирования различных планетарных орбит, и пока у меня есть проекты, я изо всех сил пытаюсь встроить анимированный сюжет в сам графический интерфейс. Сама анимация работает, но это с plt.subplots() вместо plt.Рисунок ()

Вот анимированный сюжет, который я хочу внедрить:

 import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation


global angles
angles = np.linspace(0,2*np.pi,360)


E_semi_major_axis = 149.596e6
E_eccentricity = 0.017
E_semi_latus = E_semi_major_axis*(1 - (E_eccentricity**2))

M_semi_major_axis = 227.923e6
M_eccentricity = 0.0935
M_semi_latus = M_semi_major_axis*(1 - (M_eccentricity**2))

def calc_Traj(semi_major_axis, semi_latus, eccentricity, r, x, y):
    for i in angles:
        val = semi_latus / (1   (eccentricity*np.cos(i)))
        r.append(val)
        valx = (semi_major_axis*(np.cos(i) - eccentricity))/1e8
        valy = (semi_major_axis*(np.sqrt(1 - (eccentricity**2)))*np.sin(i))/1e8

        x.append(valx)
        y.append(valy)

    return r,x,y

def cal_Traj_peri_alph(semi_major_axis, semi_latus, eccentricity):
    minmax = [0, np.pi]
    for i in minmax:
        val = semi_latus / (1   (eccentricity*np.cos(i)))
        valx = semi_major_axis*(np.cos(i) - eccentricity)

        print('For Phi = {0} we have that r={1}, x={2}'.format(i, val, valx))

##################################
E_r, E_x, E_y = [], [], []
E_r, E_x, E_y = calc_Traj(E_semi_major_axis, E_semi_latus, E_eccentricity, E_r, E_x, E_y)
print("Perihelion and Alphelion Data for Earth:")
cal_Traj_peri_alph(E_semi_major_axis, E_semi_latus, E_eccentricity)
##################################
print("Perihelion and Alphelion Data for Mars:")
M_r, M_x, M_y = [], [], []
M_r, M_x, M_y = calc_Traj(M_semi_major_axis, M_semi_latus, M_eccentricity, M_r, M_x, M_y)
cal_Traj_peri_alph(M_semi_major_axis, M_semi_latus, M_eccentricity)
##################################


fig, ax = plt.subplots()
l = plt.plot(E_x, E_y)
l = plt.plot(M_x, M_y)
ax = plt.axis([-3,3,-3,3])

EarthDot, = plt.plot([0], [np.sin(0)], 'bo')
##MarsDot, = plt.plot([0], [np.sin(0)], 'ro')
dot, = plt.plot(0,0, 'yo')

def animate1(i):
    EarthDot.set_data((E_semi_major_axis*(np.cos(i) - E_eccentricity))/1e8, (E_semi_major_axis*(np.sqrt(1 - (E_eccentricity**2)))*np.sin(i))/1e8)
    return EarthDot,

# create animation using the animate() function
myAnimation = animation.FuncAnimation(fig, animate1, frames=np.linspace(0,2*np.pi,360), 
                                      interval=10, blit=True, repeat=True)

plt.show()
 

И вот моя попытка попробовать и реализовать его (ну, просто орбита Мар):

 #---------Imports
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import tkinter as Tk
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
#---------End of imports
M_semi_major_axis = 227.923e6
M_eccentricity = 0.0935
M_semi_latus = M_semi_major_axis*(1 - (M_eccentricity**2))

global angles
angles = np.linspace(0,2*np.pi,360)

def calc_Traj(semi_major_axis, semi_latus, eccentricity, r, x, y):
    for i in angles:
        val = semi_latus / (1   (eccentricity*np.cos(i)))
        r.append(val)
        valx = (semi_major_axis*(np.cos(i) - eccentricity))/1e8
        valy = (semi_major_axis*(np.sqrt(1 - (eccentricity**2)))*np.sin(i))/1e8

        x.append(valx)
        y.append(valy)

    return r,x,y

##################################
print("Perihelion and Alphelion Data for Mars:")
M_r, M_x, M_y = [], [], []
M_r, M_x, M_y = calc_Traj(M_semi_major_axis, M_semi_latus, M_eccentricity, M_r, M_x, M_y)

##################################


fig = plt.Figure()

#x = np.arange(0, 2*np.pi, 0.01)        # x-array

def animate(i):
    MarsDot.set_data((M_semi_major_axis*(np.cos(i) - M_eccentricity))/1e8, (M_semi_major_axis*(np.sqrt(1 - (M_eccentricity**2)))*np.sin(i))/1e8)  # update the data
    return MarsDot,

root = Tk.Tk()

label = Tk.Label(root,text="Simulation").grid(column=0, row=0)

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().grid(column=0,row=1)

ax = fig.add_subplot(111)
orbitPath, = ax.plot(M_x, M_y)
MarsDot, = ax.plot(0, np.sin(0))

ani = animation.FuncAnimation(fig, animate, frames=np.linspace(0,2*np.pi,360), interval=10, blit=True)

Tk.mainloop()
 

Результат, который я получаю, — это просто встроенный график с графиком орбиты, но анимированная часть отсутствует.

На данный момент я просто хочу, чтобы встроенная анимация работала, а любые недостатки я смогу устранить и исправить позже.

Извиняюсь и заранее благодарю вас!

Ответ №1:

Ваш код работает нормально, просто вы не указали маркер MarsDot , поэтому результат невидим.

попробуйте:

 MarsDot, = ax.plot(0, np.sin(0), 'ro')  # Draws Mars' position with a red circle
 

Комментарии:

1. Большое вам спасибо! Я действительно чувствую себя идиотом. Это всегда что-то подобное.