python:使用 Ellipse类绘制椭圆

在Python中,使用 matplotlib 绘制椭圆,可以使用 Ellipse类和 add_artist方法。

编写 test_ellipse.py 如下

python 复制代码
# -*- coding: utf-8 -*-
""" 使用Ellipse类绘制椭圆 """
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

fig, ax = plt.subplots()
ellipse = Ellipse(xy=(2, 2), width=4, height=3, angle=30, color='red')
# 使用 add_artist方法绘制椭圆
ax.add_artist(ellipse)
ax.set_xlim(0, 6)
ax.set_ylim(0, 8)
plt.grid()
plt.show()

在这个例子中,Ellipse类的参数xy指定了椭圆的中心位置,width和height分别设定了椭圆的长轴和短轴,angle是椭圆的旋转角度,color定义了椭圆的颜色。add_artist方法将椭圆作为图层添加到了坐标轴上。

运行 python test_ellipse.py


《高等数学》同济大学版 P340,编写 test_oval.py 如下

python 复制代码
# -*- coding: utf-8 -*-
""" 使用 numpy 绘制椭圆 """
import numpy as np
import matplotlib.pyplot as plt
 
# 椭圆的参数方程
a, b = 5, 3  # 椭圆的长轴和短轴
theta = np.linspace(0, 2*np.pi, num=100) # 角度从0到2π
x = a * np.cos(theta)  # 中心点x坐标
y = b * np.sin(theta)  # 中心点y坐标
 
# 绘制椭圆
plt.plot(x, y, color='blue')
plt.axis('equal') # 确保x轴和y轴比例相同
plt.grid()
plt.show()

这段代码将会绘制一个中心在原点的椭圆,长轴为5,短轴为3,并显示绘图。

记得使用plt.axis('equal')来保证绘制出来的椭圆是正确的椭圆形状,

这样做可以确保x轴和y轴的单位长度相同。

运行 python test_oval.py

相关推荐
默_笙4 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003964 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫4 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技4 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读4 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时4 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊4 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1234 天前
2026年第38周GitHub趋势周报
python·科技·github
IZero074 天前
Jev 与 Laya
python·语言模型