user7288808
user7288808

Reputation: 137

R - Draw Ellipse in ScatterPlot (not* stat-ellipse)

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?

Upvotes: 5

Views: 3393

Answers (2)

Stéphane Laurent
Stéphane Laurent

Reputation: 84709

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

Upvotes: 2

Macrophage
Macrophage

Reputation: 149

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!

Upvotes: 3

Related Questions