如何在ggplot2中获取椭圆内的点? [英] How to get the points inside of the ellipse in ggplot2?

查看:106
本文介绍了如何在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()

这篇关于如何在ggplot2中获取椭圆内的点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆