Adding custom image to geom_polygon fill in ggplot

前端 未结 3 1886
臣服心动
臣服心动 2020-12-23 16:04

I was asked by a student if it was possible to recreate a plot similar to the one below using R:

\"enter

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-23 16:28

    #example data/ellipses set.seed(101) n <- 1000 x1 <- rnorm(n, mean=2) y1 <- 1.75 + 0.4*x1 + rnorm(n) df <- data.frame(x=x1, y=y1,
        group="A") x2 <- rnorm(n, mean=8) y2 <- 0.7*x2 + 2 + rnorm(n) df <-
        rbind(df, data.frame(x=x2, y=y2, group="B")) x3 <- rnorm(n, mean=6)
        y3 <- x3 - 5 - rnorm(n) df <- rbind(df, data.frame(x=x3, y=y3,
        group="C"))
    
    
    #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_polygon(data=df_ell, aes(x=x, y=y,colour=group, fill=group),
        alpha=0.1, size=1, linetype=1)
    

提交回复
热议问题