How can a data ellipse be superimposed on a ggplot2 scatterplot?

后端 未结 2 1190
有刺的猬
有刺的猬 2020-12-01 02:10

I have an R function which produces 95% confidence ellipses for scatterplots. The output looks like this, having a default of 50 points for each ellipse (50 rows):



        
2条回答
  •  情深已故
    2020-12-01 03:02

    Maybe this could help you:

    #bootstrap
    set.seed(101)
    n <- 1000
    x <- rnorm(n, mean=2)
    y <- 1.5 + 0.4*x + rnorm(n)
    df <- data.frame(x=x, y=y, group="A")
    x <- rnorm(n, mean=2)
    y <- 1.5*x + 0.4 + rnorm(n)
    df <- rbind(df, data.frame(x=x, y=y, group="B"))
    
    #calculating ellipses
    library(ellipse)
    df_ell <- data.frame()
    for(g in levels(df$group)){
    df_ell <- rbind(df_ell, cbind(as.data.frame(with(df[df$group==g,], ellipse(cor(x, y), 
                                             scale=c(sd(x),sd(y)), 
                                             centre=c(mean(x),mean(y))))),group=g))
    }
    #drawing
    library(ggplot2)
    p <- ggplot(data=df, aes(x=x, y=y,colour=group)) + geom_point(size=1.5, alpha=.6) +
      geom_path(data=df_ell, aes(x=x, y=y,colour=group), size=1, linetype=2)
    

    Output looks like this:

    enter image description here

    Here is more complex example.

提交回复
热议问题