how to draw two half circles in ggplot in r

后端 未结 2 1997
傲寒
傲寒 2020-12-14 13:03

How can I make a plot like this with two different-sized half circles (or other shapes such as triangles etc.)?

I\'ve looked into a few options: Another pos

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-14 13:26

    If you don't need to have ggplot2 map aesthetics other than x and y you could try egg::geom_custom,

    # devtools::install_github("baptiste/egg")
    library(egg)
    library(grid)
    library(ggplot2)
    
    d = data.frame(r1= c(1,3,2), r2=c(3,6,5), x=1:3, y=1:3)
    gl <- Map(mushroomGrob, r1=d$r1, r2=d$r2, gp=list(gpar(fill=c("bisque","maroon"), col="white")))
    d$grobs <- I(gl)
    
    ggplot(d, aes(x,y)) + 
      geom_custom(aes(data=grobs), grob_fun=I) +
      theme_minimal()
    

    with the following grob,

    mushroomGrob <- function(x=0.5, y=0.5, r1=0.2, r2=0.1, scale = 0.01, angle=0, gp=gpar()){
    grob(x=x,y=y,r1=r1,r2=r2, scale=scale, angle=angle, gp=gp , cl="mushroom")
    }
    
    preDrawDetails.mushroom <- function(x){
      pushViewport(viewport(x=x$x,y=x$y))
    }
    postDrawDetails.mushroom<- function(x){
      upViewport()
    }
    drawDetails.mushroom <- function(x, recording=FALSE, ...){
      th2 <- seq(0,pi, length=180)
      th1 <- th2 + pi
      d1 <- x$r1*x$scale*cbind(cos(th1+x$angle*pi/180),sin(th1+x$angle*pi/180))
      d2 <- x$r2*x$scale*cbind(cos(th2+x$angle*pi/180),sin(th2+x$angle*pi/180))
      grid.polygon(unit(c(d1[,1],d2[,1]), "snpc")+unit(0.5,"npc"), 
                  unit(c(d1[,2],d2[,2]), "snpc")+unit(0.5,"npc"),
                  id=rep(1:2, each=length(th1)), gp=x$gp)
    }
    
    
    
    # grid.newpage()
    # grid.draw(mushroomGrob(gp=gpar(fill=c("bisque","maroon"), col=NA)))
    

提交回复
热议问题