如何在Matplotlib中为置信椭圆添加长轴与短轴?
绘制置信椭圆的长轴与短轴方法
Matplotlib的Ellipse类没有内置参数可以直接显示长轴和短轴,需要手动计算轴的端点坐标,再绘制线段实现。
实现步骤
- 将椭圆的旋转角度从度转换为弧度,用于三角函数计算
- 根据椭圆中心、长/短轴长度、旋转角度,计算长轴和短轴的端点坐标
- 先绘制椭圆,再用
plot函数绘制长轴和短轴线段
完整代码示例
import matplotlib.pyplot as plt from matplotlib.patches import Ellipse import numpy as np # 定义椭圆参数 center = (0, 0) long_axis_length = 4 # 长轴总长度 short_axis_length = 2 # 短轴总长度 rotation_angle = 30 # 椭圆旋转角度(单位:度) # 角度转弧度 theta = np.deg2rad(rotation_angle) # 计算长轴两个端点 long_end1 = (center[0] + (long_axis_length/2)*np.cos(theta), center[1] + (long_axis_length/2)*np.sin(theta)) long_end2 = (center[0] - (long_axis_length/2)*np.cos(theta), center[1] - (long_axis_length/2)*np.sin(theta)) # 计算短轴两个端点(短轴与长轴垂直,向量方向为(-sinθ, cosθ)) short_end1 = (center[0] + (short_axis_length/2)*(-np.sin(theta)), center[1] + (short_axis_length/2)*np.cos(theta)) short_end2 = (center[0] - (short_axis_length/2)*(-np.sin(theta)), center[1] - (short_axis_length/2)*np.cos(theta)) # 创建画布和轴 fig, ax = plt.subplots() # 添加椭圆 ellipse = Ellipse(center, long_axis_length, short_axis_length, angle=rotation_angle, edgecolor='blue', facecolor='none') ax.add_patch(ellipse) # 绘制长轴(红色虚线) ax.plot([long_end1[0], long_end2[0]], [long_end1[1], long_end2[1]], color='red', linestyle='--', linewidth=1) # 绘制短轴(绿色虚线) ax.plot([short_end1[0], short_end2[0]], [short_end1[1], short_end2[1]], color='green', linestyle='--', linewidth=1) # 设置坐标轴等比例,避免椭圆变形 ax.set_aspect('equal') # 调整坐标轴范围,完整显示图形 ax.set_xlim(-3, 3) ax.set_ylim(-2, 2) plt.show()
说明
- 可以通过修改
plot函数的color、linestyle、linewidth参数调整轴的样式 - 若需要为置信椭圆计算参数(比如基于数据集的协方差矩阵),只需将对应的中心、长/短轴长度、旋转角度代入即可
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

