extract points/data within ellipse ggplot2

216 Views Asked by At

I am using geom_ellipse to create an ellipse on faithful dataset. Here is the code:

t <- position_nudge(x=-1,y=-0.5)

obj <- ggplot(faithful, aes(waiting, eruptions))+
  geom_point()+ geom_ellipse(aes(x0 = 70, y0 = 3, a= 3, b = 10,angle = pi/3),color="red",
                             position = t)

The graph looks like this: ellipse

I want to extract the points/data that are present within the ellipse? How can I do that? I tried what was done here , but it does not work for geom_ellipse.

1

There are 1 best solutions below

2
On

The thing with geom_ellipse is that when you look at the data of the layer with ggplot_build, you can see that the ellipse is shown multiple times in a data loop. So what you could do is get a first copy of the values like 272 values (same as your data). Based on the answer you can do the following:

library(ggplot2)
library(ggforce)
library(sp)
t <- position_nudge(x=-1,y=-0.5)
obj <- ggplot(faithful, aes(waiting, eruptions))+
  geom_point()+ geom_ellipse(aes(x0 = 70, y0 = 3, a= 3, b = 10,angle = pi/3),color="red",
                             position = t)
obj
#> Warning: Using the `size` aesthetic in this geom was deprecated in ggplot2 3.4.0.
#> ℹ Please use `linewidth` in the `default_aes` field and elsewhere instead.

# Extract components
build <- ggplot_build(obj)$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[1:272], ell$y[1:272]))
)

# Plot the result
ggplot(dat, aes(x, y)) +
  geom_point(aes(col = in.ell)) +
  geom_ellipse(aes(x0 = 70, y0 = 3, a= 3, b = 10,angle = pi/3),color="red",
               position = t)

Created on 2022-12-17 with reprex v2.0.2

When you check the dat dataframe, you can see which points are in the ellipse.