Fill superimposed ellipses in ggplot2 scatterplots

10,559

As mentioned in the comments, polygon is needed here:

qplot(data = df, x = x, y = y, colour = class) + 
  stat_ellipse(geom = "polygon", alpha = 1/2, aes(fill = class))

enter image description here

Share:
10,559

Related videos on Youtube

QkuCeHBH
Author by

QkuCeHBH

Updated on September 14, 2022

Comments

  • QkuCeHBH
    QkuCeHBH over 1 year

    This question is a follow-up of "How can a data ellipse be superimposed on a ggplot2 scatterplot?".

    I want to create a 2D scatterplot using ggplot2 with filled superimposed confidence ellipses. Using the solution of Etienne Low-Décarie from the above mentioned post, I do get superimposed ellipses to work. The solution is based on stat_ellipse available from https://github.com/JoFrhwld/FAAV/blob/master/r/stat-ellipse.R

    Q: How can I fill the inner area of the ellipse(s) with a certain color (more specifically I want to use the color of the ellipse border with some alpha)?

    Here is the minimal working example modified from the above mentioned post:

    # create data
    set.seed(20130226)
    n <- 200
    x1 <- rnorm(n, mean = 2)
    y1 <- 1.5 + 0.4 * x1 + rnorm(n)
    x2 <- rnorm(n, mean = -1)
    y2 <- 3.5 - 1.2 * x2 + rnorm(n)
    class <- rep(c("A", "B"), each = n)
    df <- data.frame(x = c(x1, x2), y = c(y1, y2), colour = class)
    
    # get code for "stat_ellipse"
    library(devtools)
    library(ggplot2)
    source_url("https://raw.github.com/JoFrhwld/FAAV/master/r/stat-ellipse.R")
    
    # scatterplot with confidence ellipses (but inner ellipse areas are not filled)
    qplot(data = df, x = x, y = y, colour = class) + stat_ellipse()
    

    Output of working example: image of example output

    • Arun
      Arun about 11 years
      The geom seems to be path by default in stat_ellipse implementation. I wonder if path can have fill options...