Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

python - Plotting an ellipse with a self-written function

I know that there is an ellipse function in matplotlib. But I am trying to learn more Python, so I wanted to write a function for ellipse and then plot it. It turns out that I could not do it. I have this, but it does not give me an ellipse:

def elipse(x,y):
    return (x - a)**2/a**2 + (y - a)**2/b**2 - 1

a = 5
b = 8
x = np.linspace(1,100)
y = np.linspace(1,100)
ell = elipse(x,y)
plt.plot(ell)

I would like to plot it for example giving it an origin point and a and b (width and height).

question from:https://stackoverflow.com/questions/65876318/plotting-an-ellipse-with-a-self-written-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As you only create an implicit equation, you could use sympy, Python's symbolic math library. Default plot_implicit() will plot for x and y between -5 and 5, but you can change the limits. To just show one plot, use plot_implicit(ellipse(x, y), (x, -2, 10), (y, -2, 10)). To create subplots, show=False and PlotGrid can be used:

from sympy.plotting import plot_implicit, PlotGrid, plot
from sympy.abc import x, y

def ellipse(x, y):
    return (x - a) ** 2 / a ** 2 + (y - a) ** 2 / b ** 2 - 1

a = 4
b = 3

p1 = plot_implicit(ellipse(x, y), (x, -2, 10), (y, -2, 10), axis_center=(0, 0), show=False)
p2 = plot_implicit(ellipse(x, y), (x, -2, 20), (y, -1, 7), axis_center=(0, 0), show=False)
PlotGrid(1, 2, p1, p2)

resulting plot

Both plots show the same ellipse, with the leftmost point at 0, 4 and the topmost point at 4, 7. If you want another ellipse, you can change the values of a and b, or change the equation in another way.

By the way, plot_implicit seems to default draw the x-axis at the center of the plot and the y-axis at x=0. Usually, sympy's plotting also draws the x-axis at y=0. I don't know whether this is only in the current version, but it really looks strange with the x-axis in the center. The crossing can be set explicitly as 0,0 with axis_center=(0, 0).

Alternatively, you could create a grid with numpy and plot a contour with matplotlib.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...