Issue
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).
Solution
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)
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.
Answered By - JohanC
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.