4

I have a scatter plot created using ggplot in R:

ggplot(data, aes(x=x, y=y)) + 
  xlim(0,800) + 
  ylim(0,600) + 
  geom_point(colour="black") + 
  geom_path(aes(color="red")

I want to draw an ellipse overlaid on this plot (please, not confidence interval ellipse) using center coordinates, height, and width.

I've tried draw.ellipse function from plotrix package, but this only works on scatterplot created by R's default plot function.

Would anyone know how to draw an ellipse on a scatterplot created by ggplot?

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
user7288808
  • 117
  • 2
  • 8
  • Can you elaborate on why `stat_ellipse()` doesn't work for you? – Z.Lin Sep 05 '18 at 10:32
  • @Z.Lin Sure. I believe stat_ellipse() draw an ellipse around clusters of one's data. (i.e. "norm"). Instead, what I am trying to do is draw an ellipse at any coordinates, not* necessarily according to the plot of data. Does that help? Let me know if it needs elaboration. – user7288808 Sep 05 '18 at 14:25
  • You may want to try `geom_ellipsis` from the `ggforce` package (dev version on Github, vignette with description of this function can be found [here](https://github.com/thomasp85/ggforce/blob/master/vignettes/Visual_Guide.Rmd)) – Z.Lin Sep 05 '18 at 15:24
  • @Z.Lin, hello. I can't get geom_ellipsis() from ggforce package to work. R doesn't recognize it, have you used this package before? – user7288808 Jan 11 '19 at 16:07
  • @user7288808 please define "R doesn't recognize it". Cite the exact R error message (if any). – January Jul 12 '19 at 05:35

2 Answers2

2

I just encountered the very same problem today! Here's the solution for your case. First, make sure that you created the scatterplot with ggplot2, then download and import the ggforce package. Add

geom_ellipse(aes(x0=x, y0=y, a=axis length on x direction, b=axis on y direction), fill=..., alpha=...)+geom_polygon()

for a filled, translucent ellipse at (x,y). If you don't want it to be filled, just cut out the fill and alpha parameter and replace geom_polygon() with geom_path().

Hope this helps!

Macrophage
  • 139
  • 9
1

Here is a solution with the PlaneGeometry package (soon on CRAN).There are multiple ways to define an ellipse with this package. The "direct" way consists in providing the center, the major radius, the minor radius, and the angle alpha between the horizontal axis and the major axis (in degrees by default).

library(ggplot2)
library(PlaneGeometry)

# define an ellipse
ell <- Ellipse$new(center = c(6,4), rmajor = 2, rminor = 1, alpha = 30)
# ellipse as a path
ellpath <- ell$path()
# the path is not closed; close it
ellpath <- rbind(ellpath, ellpath[1,])

ggplot() +
  geom_point(aes(x = Sepal.Length, y = Petal.Length), iris) +
  geom_path(aes(x = x, y = y), as.data.frame(ellpath), color = "red")

enter image description here

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225