Home > Enterprise >  Drawing an ellipse at an angle between two points in Python
Drawing an ellipse at an angle between two points in Python

Time:01-18

I'm trying to draw an ellipse between two points. So far, I have it mostly working:

Arc Angle

The issue comes with setting the ellipse height (ellipse_h below).

    x = center_x   radius*np.cos(theta deg)
    y = center_y - ellipse_h * radius*np.sin(theta deg)

In this example, it's set to -0.5: Ellipse Height

Can anyone please help me rotate the ellipse height with the ellipse? Thank you!

import numpy as np
import matplotlib.pyplot as plt

def distance(x1, y1, x2,  y2):
    return np.sqrt(np.power(x2 - x1, 2)   np.power(y2 - y1, 2) * 1.0)

def midpoint(x1, y1, x2,  y2):
    return [(x1   x2) / 2,(y1   y2) / 2]

def angle(x1, y1, x2, y2):
    #radians
    return np.arctan2(y2 - y1, x2 - x1)

x1 = 100
y1 = 150
x2 = 200
y2 = 190
ellipse_h = -1
x_coords = []
y_coords = []

mid = midpoint(x1, y1, x2, y2)
center_x = mid[0]
center_y = mid[1]
ellipse_resolution = 40
step = 2*np.pi/ellipse_resolution

radius = distance(x1, y1, x2, y2) * 0.5
deg = angle(x1, y1, x2, y2)
cos = np.cos(deg * np.pi /180)
sin = np.sin(deg * np.pi /180)

for theta in np.arange(0, np.pi step, step):
    x = center_x   radius*np.cos(theta deg)
    y = center_y - ellipse_h * radius*np.sin(theta deg)
    x_coords.append(x)
    y_coords.append(y)

plt.xlabel("X")
plt.ylabel("Y")
plt.title("Arc between 2 Points")

plt.plot(x_coords,y_coords)
plt.scatter([x1,x2],[y1,y2])
plt.axis('equal')

plt.show()

CodePudding user response:

A simple solution is to describe the ellipse by its ellipse_outputs

Following your comment, for the limiting case of the circle, you need to specify height = np.sqrt((x2 - x1)**2 (y2 - y1)**2), so that a = b.

Hope this helps !

  • Related