Plotting elliptical orbits

只谈情不闲聊 提交于 2019-11-30 17:26:42

问题


I'm trying to write a code that plots the elliptical paths of an object using the equation for the ellipse r=a(1-e^2)/(1+e*cos(theta)). I'd also like this data to be put into an array for other use.

from numpy import *#Imports Python mathematical functions library
import matplotlib.pyplot as plt #Imports plot library
from pylab import *

a = 5
e = 0.3
theta = 0
while theta <= 2*pi:
    r = (a*(1-e**2))/(1+e*cos(theta))
    print("r = ",r,"theta = ",theta)
    plt.polar(theta, r)
    theta += pi/180

plt.show()

The code spits out correct values for r and theta, but the plot is blank. The polar plot window appears, but there is nothing plotted.

Please help. Thanks in advance.


回答1:


Do not call plt.polar once for every point. Instead, call it once, with all the data as input:

import numpy as np #Imports Python mathematical functions library
import matplotlib.pyplot as plt #Imports plot library
cos = np.cos
pi = np.pi

a = 5
e = 0.3
theta = np.linspace(0,2*pi, 360)
r = (a*(1-e**2))/(1+e*cos(theta))
plt.polar(theta, r)

print(np.c_[r,theta])

plt.show()


By the way, numpy can do the calculation as a two-liner, instead of using a while-loop:

theta = np.linspace(0,2*pi, 360)   # 360 equally spaced values between 0 and 2*pi
r = (a*(1-e**2))/(1+e*cos(theta))  

This defines theta and r as numpy arrays (rather than single values).




回答2:


I think you need to do points.append([theta,r]) then at the end plt.polar(points) ... that makes a kinda neat design too

from numpy import *#Imports Python mathematical functions library
import matplotlib.pyplot as plt #Imports plot library
from pylab import *

a = 5
e = 0.3
theta = 0

points = []
while theta <= 2*pi:
    r = (a*(1-e**2))/(1+e*cos(theta))
    print("r = ",r,"theta = ",theta)
    points.append((theta, r))
    theta += pi/180
#plt.polar(points) #this is cool but probably not what you want
plt.polar(*zip(*points))
plt.show()


来源:https://stackoverflow.com/questions/12375609/plotting-elliptical-orbits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!