Rotating ellipse in python using x,y,theta

Question:

I’m trying to draw an ellipse in python using the following equations:

xpos = a*np.cos(theta)
ypos = b*np.sin(theta)

Ellipse

This works, but when I try to rotate the resulting ellipse using:

xpos = xpos*np.cos(np.pi/2)+ypos*np.sin(np.pi/2)
ypos = -xpos*np.sin(np.pi/2)+ypos*np.cos(np.pi/2)

The ellipse becomes a line, rather than just rotated by 90 degrees. What is causing this?Rotated ellipse

Asked By: Dominique Petit

||

Answers:

Your problem is that you’re redefining xpos first and using that one for your new ypos, basically you’re not doing the transformation of coordinates simultaneously.

If you create new variables for the points in the new coordinate system them you get the rotated ellipse.

import numpy as np
import matplotlib.pyplot as plt

theta = np.arange(0, 2*np.pi, 0.01)
a = 1
b = 2

xpos = a*np.cos(theta)
ypos = b*np.cos(theta)

new_xpos = xpos*np.cos(np.pi/2)+ypos*np.sin(np.pi/2)
new_ypos = -xpos*np.sin(np.pi/2)+ypos*np.cos(np.pi/2)

plt.plot(xpos, ypos, 'b-')
plt.plot(new_xpos, new_ypos, 'r-')

plt.show()

For anyone thinking there’s something wrong with the code from @Ignacio, ypos should be, ypos= b*np.sin(theta)

Hence,

import numpy as np
import matplotlib.pyplot as plt

theta = np.arange(0, 2*np.pi, 0.01)

a = 1
b = 2

xpos = a*np.cos(theta)
ypos = b*np.sin(theta)

new_xpos = xpos*np.cos(np.pi/2)+ypos*np.sin(np.pi/2)
new_ypos = -xpos*np.sin(np.pi/2)+ypos*np.cos(np.pi/2)

plt.plot(xpos,ypos, 'b')
plt.plot(new_xpos,new_ypos, 'r')
plt.axis('equal')
plt.show()
Answered By: Nicole Krumm
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.