Matplotlib trying to draw a circle though basic equation ( x**2 + y**2 = 9)

Viewed 524

I am trying to plot some mathematical equations. Using code below gave almost lilke an ellipse instead of a circle. Is there a way to improve the shape ..i tried increasing steps. Not sure if another module would be better or really needed ? Also can i just give the equation as an input somehow ..so i dont have to use np.sqrt. I went through some of already answered questions but either they are too specific or too complex. So kindly dont mark it a duplicate. Just looking for a genric solution here as I would need to plot parabola and hyperbola as well.

import numpy as np
import matplotlib.pyplot as plt
    
x = np.arange(0, 1000 , 0.001)
y = np.sqrt(9 - np.power(x,2))

# Plot the points using matplotlib
plt.plot(x, y)

plt.show()

======================================================= Using some suggestions, Tried to plot y and -y as well.. but circle doesn't complete on left side.

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-10, 10, 0.01)
y = np.sqrt(9 - np.power(x, 2))

# Plot the points using matplotlib
plt.gca().set_aspect('equal')
plt.plot(x, y)
plt.plot(x, -y)
plt.show()
1 Answers

First of all you need to set a linspace which contains all values you need, i saw that you tried to plot a radius 3 circle.

x = np.linspace(-5.0, 5.0, 1000)
y = np.linspace(-5.0, 5.0, 1000)

After that, make a meshgrid with numpy and use matplotlib to plot your contour. Notice that F is your circle equation.

X, Y = np.meshgrid(x,y)

F = X**2 + Y**2 - 9.0

Finally, just call matplotlib and plot your figure as a contour.

fig, ax = plt.subplots()

ax.contour(X,Y,F,[0])

ax.set_aspect(1)

plt.title('My Circle', fontsize=8)

plt.xlim(-10,10)
plt.ylim(-10,10)

plt.grid(linestyle='--')

plt.show()
Related