首页 > 解决方案 > 如何使用 matplotlib 绘制半圆

问题描述

我想用 matplotlib 画一个半圆。

在这里我有一个法庭

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)

在此处查看图片:

场地

我想添加一个半圆,该半圆在点 (0,50) 处出现,半径 = 10。结果应该是这样的:

预期产出

标签: python-3.xmatplotlib

解决方案


这是一个绘制半圆的函数,使用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()

在此处输入图像描述


推荐阅读