Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a semicircle using matplotlib

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:

Field

I want to add one semicircle that stars at point (0,50) with radius = 10. The result should be something like this:

Expected output

like image 207
jalazbe Avatar asked Sep 03 '26 00:09

jalazbe


1 Answers

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

example:

x,y = generate_semicircle(0,50,10, 0.1)
plt.plot(x, y)
plt.show()

enter image description here

like image 170
warped Avatar answered Sep 05 '26 11:09

warped



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!