环境
pycharm2023.1.2,window10
方法
- 安装依赖
pip install matplotlib
pip install numpy
- 代码
原理,先假设圆半径为2cm,圆心为x,y轴的原点,那圆的直径则为正方形的对角线长,再根据勾股定理算出边长,有了边长则可以计算出4个顶点的位置
下面为正方形在内的代码
import matplotlib.pyplot as plt
import numpy as np
# 圆的半径
radius = 2.0
# 计算圆心
center_x, center_y = 0.0, 0.0
# 创建一个角度数组,用于绘制圆
theta = np.linspace(0, 2 * np.pi, 100)
# 计算圆的 x 和 y 坐标
circle_x = center_x + radius * np.cos(theta)
circle_y = center_y + radius * np.sin(theta)
# 计算正方形的边长(对角线长度等于圆的直径)
square_side_length = 2 * radius / np.sqrt(2)
# 计算正方形的顶点坐标
square_x = [center_x - square_side_length / 2, center_x + square_side_length / 2,
center_x + square_side_length / 2, center_x - square_side_length / 2,
center_x - square_side_length / 2]
square_y = [center_y + square_side_length / 2, center_y + square_side_length / 2,
center_y - square_side_length / 2, center_y - square_side_length / 2,
center_y + square_side_length / 2]
# 创建图形
plt.figure(figsize=(6, 6))
# 绘制圆
plt.plot(circle_x, circle_y, label='Circle')
# 绘制正方形
plt.plot(square_x, square_y, label='Square', color='red')
# 设置图形的标题和标签
plt.title('Square around a Circle')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()
# 设置轴的比例相同
plt.axis('equal')
# 显示图形
plt.show()
下面为正方形在圆外的代码
import matplotlib.pyplot as plt
import numpy as np
# 圆的半径
radius = 2
# 正方形的边长,这里我们让正方形的边长等于圆的直径
side_length = 2 * radius
# 创建一个图形和坐标轴
fig, ax = plt.subplots()
# 绘制圆
circle = plt.Circle((0, 0), radius, edgecolor='blue', facecolor='none')
ax.add_artist(circle)
# 正方形的四个顶点
square_vertices = [
(-radius, -radius),
( radius, -radius),
( radius, radius),
(-radius, radius)
]
# 绘制正方形
square = plt.Polygon(square_vertices, edgecolor='red', facecolor='none')
ax.add_patch(square)
# 设置坐标轴的显示范围
ax.set_xlim(-side_length, side_length)
ax.set_ylim(-side_length, side_length)
# 等比例显示
ax.set_aspect('equal')
plt.title('Square around a Circle')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# 显示图形
plt.show()