Search code examples
rggplot2geom-bar

ggplot2: Shift the baseline of barplot (geom_bar) to the minimum data value


I'm trying to generate a bar plot using geom_bar. My bars have both negative and positive values:

set.seed(1)
df <- data.frame(y=log(c(runif(6,0,1),runif(6,1,10))),se=runif(12,0.05,0.1),name=factor(rep(c("a","a","b","b","c","c"),2),levels=c("a","b","c")),side=factor(rep(1:2,6),levels=1:2),group=factor(c(rep("x",6),rep("y",6)),levels=c("x","y")),stringsAsFactors=F)

This plot command plots the positive bars to face up and the negative ones to face down:

library(ggplot2)
dodge <- position_dodge(width=0.9)
limits <- aes(ymax=y+se,ymin=y-se)
ggplot(df,aes(x=name,y=y,group=interaction(side,name),col=group,fill=group))+facet_wrap(~group)+geom_bar(width=0.6,position=position_dodge(width=1),stat="identity")+
geom_bar(position=dodge,stat="identity")+geom_errorbar(limits,position=dodge,width=0.25)

enter image description here

My question is how do I set the base line to the minimum of all bars instead of at 0 and therefre have the red bars facing up?


Solution

  • This simple hack also works:

    m <- min(df$y) # find min
    df$y <- df$y - m
    ggplot(df,aes(x=name,y=y,group=interaction(side,name),col=group,fill=group))+
      facet_wrap(~group)+
      geom_bar(width=0.6,position=position_dodge(width=1),stat="identity")+
      geom_bar(position=dodge,stat="identity")+
      geom_errorbar(limits,position=dodge,width=0.25) +
      scale_y_continuous(breaks=seq(min(df$y), max(df$y), length=5),labels=as.character(round(seq(m, max(df$y+m), length=5),2))) # relabel
    

    enter image description here