如何在ggplot2中获取椭圆内的点?
我正在尝试确定情节中最密集的区域.我使用ggplot2中的stat_ellipse()
进行此操作.但是我无法获取椭圆内部点的信息(总和,每个点的订单号等).
I'm trying to identify the densest region in the plot. And I do this using stat_ellipse()
in ggplot2. But I can not get the information (sum total, order number of each point and so on) of the points inside of the ellipse.
很少看到有关此问题的讨论.这可能吗?
Seldom see the discussion about this problem. Is this possible?
例如:
ggplot(faithful, aes(waiting, eruptions))+
geom_point()+
stat_ellipse()
此处是Roman的建议. stat_ellipse
的帮助说它使用了car::ellipse
的修改版本,因此我选择从ggplot
对象中提取椭圆点.这样,它应该总是正确的(即使在stat_ellipse
中更改选项,也是如此).
Here is Roman's suggestion implemented. The help for stat_ellipse
says it uses a modified version of car::ellipse
, so therefore I chose to extract the ellipse points from the ggplot
object. That way it should always be correct (also if you change options in 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()