Search code examples
rplotggplot2coordinate

ggplot: how to move the 0 coordinate to the middle of X-axis?


enter image description here

I am trying to create a volcano plot using the following code, but I would like to put the "0" coordinate to the middle of the X-axis. Is there a way to do this in ggplot?

v<-ggplot(exprData.fil,aes(Effect,Effect.sig))+geom_point(aes(colour=Effect.sig),alpha=0.7)+scale_colour_gradient(low="red",high="green")
    v+ggtitle(mainTitle)
    v+xlab(expression(log[2](bar(After) / bar(Before))))+ylab(expression(-log[10]("p.value"))) 

Solution

  • Add scale_x_continuous() to set the axis limits:

    v <- ggplot(exprData.fil,aes(Effect,Effect.sig)) +
           geom_point(aes(colour=Effect.sig),alpha=0.7) +
           scale_colour_gradient(low="red",high="green") +
           ggtitle(mainTitle) + 
           xlab(expression(log[2](bar(After) / bar(Before)))) +
           ylab(expression(-log[10]("p.value"))) +
           scale_x_continuous(limits=c(-12,12), breaks=seq(-12,12,2))
    

    Another option is to use coord_cartesian(xlim=c(-12,12)). The main difference between that and scale_x_continuous() is if you add any data summaries to a plot (like a smoother, mean, boxplot, etc.). If your axis limits don't include the full range of the data values, then using scale_x_continuous() (or scale_y_continuous()) will result in the data summary operation excluding the non-visible data from the summary, while coord_cartesian() will include all data in the summary, whether visible in the plot or not.