要基于生成绘图的函数创建动画吗

2024-04-23 11:10:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在一起运行一系列情节的基础上创建一个动画。我只是不知道如何让它为我的目的工作,这就是我正在尝试使用的代码。它会生成一系列情节,但我希望它能创建一个动画

pi = 3.14159

velocity = 220 #kilometers per second

def dtheta(r): #creating a function that gives angular velocity based on distance from galactic center

 dtheta = velocity/r #This function comes from the equation for angular velocity, ω=v/r, and ω = 
dtheta/dt, which is what our function represents
    return dtheta


#Creating frames at specific times for a set of distances

velocity = 220 #in km/s or pc/My

frames = 11
tstart = 0 #in units of Million Years
tfinal = 1

Stars= 25 #The number of stars being observed, equally spaced from 2 to 20 parsecs from the galactic center

t = np.linspace(tstart,tfinal,frames)
r = np.linspace(2,20,Stars)

TimeMatrix = []

for k in t: 
    snapshot = list([k*dtheta(r) for r in r]) # creating a list of the positions of a set of stars for a given time = k
    print()
    print('t =', k, 'Million Years')
    plt.axes(projection = 'polar')
    plt.ylim(0,22)
    plt.plot(snapshot, r, 'ok')
    plt.show()

    TimeMatrix.append(list(snapshot))


def plotfunction(n):
    plt.axes(projection = 'polar')
    plt.ylim(0,22)
    return plt.plot(TimeMatrix[n],r,'ok')

plotfunction(1) #needs integer input, pulls out the nth frame of the above series of plots

什么都行,谢谢


1条回答
网友
1楼 · 发布于 2024-04-23 11:10:54

这里有一种方法:

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

pi = 3.14159

velocity = 220 #kilometers per second

def dtheta(r): #creating a function that gives angular velocity based on distance from galactic center
    dtheta = velocity/r #This function comes from the equation for angular velocity, ω=v/r, and ω = 
    #dtheta/dt, which is what our function represents
    return dtheta


#Creating frames at specific times for a set of distances

velocity = 220 #in km/s or pc/My

frames = 11
tstart = 0 #in units of Million Years
tfinal = 1

Stars= 25 #The number of stars being observed, equally spaced from 2 to 20 parsecs from the galactic center

t = np.linspace(tstart,tfinal,frames)
r = np.linspace(2,20,Stars)

plt.figure(figsize=(12,4))
plt.axes(projection = 'polar')
plt.ylim(0,22)
snapi = plt.plot([t[0]*dtheta(i) for i in r] , r, 'ok', lw=1.5)

plt.ion()   # set interactive mode
plt.show()


for i,snap in enumerate(t):
#     for l in snapi:
#         l.remove()
#         del l
    snapp=[snap*dtheta(k) for k in r] 
    snapi = plt.plot(snapp, r, 'ok', lw=1.5)
    plt.legend()
    plt.gcf().canvas.draw()
    plt.pause(2)

相关问题 更多 >