Boxplot, how to match outliers' color to fill aesthetics?

后端 未结 4 1125
独厮守ぢ
独厮守ぢ 2020-12-15 20:22

I am trying to match boxplot\'s outliers color to the fill color which is set by aesthetic (scale_colour_discrete).

Here is an example.

m <- ggplo         


        
4条回答
  •  一生所求
    2020-12-15 21:07

    I found a way to do this, editing raw grid object.

    library(ggplot2)
    
    match.ol.col <- function(plt,aes.cp='fill') {
      # matches outliers' color to either fill or colour aesthetics
      #   plt: ggplot layer object having boxplot
      #   aes.cp: aetsthetic from which copy color.  must be either 'fill' or 'col'
      # returns grid objects, so print it wigh grid.draw(), not print()
      if (aes.cp %in% c('color', 'colour')) aes.cp <- 'col'
      grob <- ggplotGrob(plt)
      bps <- getGrob(grob, 'boxplots', grep=T)
      for (bp in bps$children) {
        p <- getGrob(bp, 'point', grep=T)
        if (is.null(p)) next
        r <- getGrob(bp, 'rect', grep=T)
        grob <- geditGrob(grob, p$name, gp=gpar(col=r$gp[[aes.cp]]))
      }
      return(grob)
    }
    
    
    m <- ggplot(movies, aes(y = votes, x = factor(round(rating)),
        colour=factor(Animation)))
    p <- m + geom_boxplot() + scale_y_log10()
    
    grob <- match.ol.col(p, aes.cp='colour')
    grid.draw(grob)
    

    results:

    demobox.png

提交回复
热议问题