Reputation: 2005
I want to draw a semicircle using matplotlib.
Here I have a court
import numpy as np
import matplotlib.pyplot as plt
x_asix = np.array([0,0,100,100, 0])
y_asix = np.array([0,100,100,0, 0])
x_coordenates = np.concatenate([ x_asix])
y_coordenates = np.concatenate([y_asix])
plt.plot(x_coordenates, y_coordenates)
See image here:
I want to add one semicircle that stars at point (0,50) with radius = 10. The result should be something like this:
Upvotes: 6
Views: 10594
Reputation: 11603
There is a nice example on tutorialspoint.com.
import matplotlib.pyplot as plt
from matplotlib.patches import Wedge, Rectangle
fig, ax = plt.subplots(1, 1)
ax.set_aspect('equal')
ax.set_xlim([0, 100])
ax.set_ylim([0, 100])
theta1, theta2 = -90, 90
radius = 10
center = (0, 50)
w = Wedge(center, radius, theta1, theta2, fc='none', edgecolor='black')
ax.add_patch(w)
plt.show()
Note that patches include other shapes such as Rectangle that you might find useful.
Upvotes: 3
Reputation: 26886
You could simply use the equation of the ellipse, to easily draw the portion of the ellipse you are interested in.
If you want to draw the part of the ellipse you have in your image, unfortunately you cannot simply write it as: y = f(x)
, but you can use the common trick of plotting x = f(y)
instead:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.set_aspect('equal')
x_asix = np.array([0,0,100,100, 0])
y_asix = np.array([0,100,100,0, 0])
x_coordenates = np.concatenate([ x_asix])
y_coordenates = np.concatenate([y_asix])
ax.plot(x_coordenates, y_coordenates)
# ((x - x0) / a) ** 2 + ((y - y0) / b) ** 2 == 1
a = 20
b = 15
x0 = 50
y0 = 0
x = np.linspace(-a + x0, a + x0)
y = b * np.sqrt(1 - ((x - x0) / a) ** 2) + y0
ax.plot(y, x)
Upvotes: 3
Reputation: 9482
Here is a function that draws semicircles, using numpy
:
import matplotlib.pyplot as plt
import numpy as np
def generate_semicircle(center_x, center_y, radius, stepsize=0.1):
"""
generates coordinates for a semicircle, centered at center_x, center_y
"""
x = np.arange(center_x, center_x+radius+stepsize, stepsize)
y = np.sqrt(radius**2 - x**2)
# since each x value has two corresponding y-values, duplicate x-axis.
# [::-1] is required to have the correct order of elements for plt.plot.
x = np.concatenate([x,x[::-1]])
# concatenate y and flipped y.
y = np.concatenate([y,-y[::-1]])
return x, y + center_y
x,y = generate_semicircle(0,50,10, 0.1)
plt.plot(x, y)
plt.show()
Upvotes: 6