我正在尝试确定图中最密集的区域。我在 ggplot2 中使用此方法stat_ellipse()
。但我无法获取椭圆内部点的信息(总和、每个点的序号等)。
很少看到关于这个问题的讨论。这可能吗?
例如:
ggplot(faithful, aes(waiting, eruptions))+
geom_point()+
stat_ellipse()
Run Code Online (Sandbox Code Playgroud)
这是罗马的建议的实施。的帮助stat_ellipse
说它使用 的修改版本car::ellipse
,因此我选择从ggplot
对象中提取椭圆点。这样它应该始终是正确的(即使您更改 中的选项也是如此stat_ellipse
)。
# Load packages
library(ggplot2)
library(sp)
# Build the plot first
p <- ggplot(faithful, aes(waiting, eruptions)) +
geom_point() +
stat_ellipse()
# Extract components
build <- ggplot_build(p)$data
points <- build[[1]]
ell <- build[[2]]
# Find which points are inside the ellipse, and add this to the data
dat <- data.frame(
points[1:2],
in.ell = as.logical(point.in.polygon(points$x, points$y, ell$x, ell$y))
)
# Plot the result
ggplot(dat, aes(x, y)) +
geom_point(aes(col = in.ell)) +
stat_ellipse()
Run Code Online (Sandbox Code Playgroud)