You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取ggplot2中geom_ellipse椭圆内的faithful数据集点?

提取geom_ellipse椭圆内的数据点

要提取你手动绘制的椭圆内的点,需要先考虑位置偏移和旋转椭圆的数学条件,具体步骤如下:

1. 确定椭圆的实际参数

你用了position_nudge(x=-1,y=-0.5),所以椭圆的实际中心不是代码里的(70,3),而是偏移后的坐标:

  • 实际中心:(70-1, 3-0.5) = (69, 2.5)
  • 半轴长度:a=3,b=10
  • 旋转角度:θ=π/3

2. 用旋转椭圆的不等式筛选点

对于中心在(h,k)、旋转角度为θ、半轴为a和b的椭圆,点(x,y)在椭圆内的条件是:

[(x-h)cosθ + (y-k)sinθ]^2 / a² + [-(x-h)sinθ + (y-k)cosθ]^2 / b² ≤ 1

把参数代入,直接在R里计算筛选:

# 定义椭圆的实际参数
h <- 70 - 1  # 原x0加上nudge_x
k <- 3 - 0.5 # 原y0加上nudge_y
a <- 3
b <- 10
theta <- pi/3

# 计算每个点是否在椭圆内
faithful$inside_ellipse <- with(faithful, {
  dx <- waiting - h
  dy <- eruptions - k
  # 代入旋转椭圆的不等式
  term1 <- (dx * cos(theta) + dy * sin(theta))^2 / (a^2)
  term2 <- (-dx * sin(theta) + dy * cos(theta))^2 / (b^2)
  term1 + term2 <= 1
})

# 提取椭圆内的点
inside_points <- subset(faithful, inside_ellipse)

3. 验证结果(可选)

可以画图验证筛选出的点是否正确:

ggplot(faithful, aes(waiting, eruptions)) +
  geom_point() +
  geom_ellipse(aes(x0 = 70, y0 = 3, a=3, b=10, angle=pi/3), 
               color="red", position=position_nudge(x=-1,y=-0.5)) +
  geom_point(data=inside_points, color="blue", size=2) # 蓝色点为椭圆内的点

之前的方法无效是因为那些方案大多针对stat_ellipse(基于数据统计生成的置信椭圆),而你用的geom_ellipse是手动指定参数的椭圆,需要直接用椭圆的数学公式来判断点的位置。

内容的提问来源于stack exchange,提问作者user3138373

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 11:45:33