Put whisker ends on boxplot

前端 未结 3 2028
南笙
南笙 2020-11-30 00:35

I would like to put perpendicular lines at the ends of the whiskers like the boxplot function automatically gives.

3条回答
  •  既然无缘
    2020-11-30 01:03

    It might be possible to use stat_boxplot to calculate the whisker ends, but I am not enough of a ggplot2 wizard, so I use the base function for that.

    set.seed(42)
    df <- data.frame(cond = factor( rep(c("A","B"), each=500) ), 
                     value = c(rnorm(500,mean=1,sd=0.2),rnorm(500, mean=1.5,sd=0.1)))
    
    
    whisk <- function(df,cond_col=1,val_col=2) {
      require(reshape2)
      condname <- names(df)[cond_col]
      names(df)[cond_col] <- "cond" 
      names(df)[val_col] <- "value"
      b <- boxplot(value~cond,data=df,plot=FALSE)
      df2 <- cbind(as.data.frame(b$stats),c("min","lq","m","uq","max"))
      names(df2) <- c(levels(df$cond),"pos")
      df2 <- melt(df2,id="pos",variable.name="cond")
      df2 <- dcast(df2,cond~pos)  
      names(df2)[1] <- condname
      df2
    }
    
    
    
    library(ggplot2)
    
    plot1 <- ggplot(df, aes(x=cond)) 
    plot1 <- plot1 + geom_errorbar(aes(ymin=min,ymax=max),data=whisk(df),width = 0.5)
    plot1 <- plot1 + geom_boxplot(aes(y=value))
    plot1
    

    boxplot with horizontal at whisker ends

提交回复
热议问题