Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align x axes of box plot and line plot using ggplot

Tags:

r

ggplot2

Im trying to align the x-axes of a bar plot and line plot in one window frame using ggplot. Here is the fake data I'm trying to do it with.

library(ggplot2)
library(gridExtra)
m <- as.data.frame(matrix(0, ncol = 2, nrow = 27))
colnames(m) <- c("x", "y")
for( i in 1:nrow(m))
{
  m$x[i] <- i
  m$y[i] <- ((i*2) + 3)
}

My_plot <- (ggplot(data = m, aes(x = x, y = y)) + theme_bw())
Line_plot <- My_plot + geom_line()
Bar_plot <- My_plot + geom_bar(stat = "identity")

grid.arrange(Line_plot, Bar_plot)

Thank you for your help.

like image 880
JakeC Avatar asked Feb 11 '23 01:02

JakeC


2 Answers

@eipi10 answers this particular case, but in general you also need to equalize the plot widths. If, for example, the y labels on one of the plots take up more space than on the other, even if you use the same axis on each plot, they will not line up when passed to grid.arrange:

axis <- scale_x_continuous(limits=range(m$x))

Line_plot <- ggplot(data = m, aes(x = x, y = y)) + theme_bw() + axis + geom_line()

m2 <- within(m, y <- y * 1e7)
Bar_plot <- ggplot(data = m2, aes(x = x, y = y)) + theme_bw() + axis + geom_bar(stat = "identity")

grid.arrange(Line_plot, Bar_plot)

enter image description here

In this case, you have to equalize the plot widths:

Line_plot <- ggplot_gtable(ggplot_build(Line_plot))
Bar_plot <- ggplot_gtable(ggplot_build(Bar_plot))

Bar_plot$widths <-Line_plot$widths 

grid.arrange(Line_plot, Bar_plot)

enter image description here

like image 96
Matthew Plourde Avatar answered Feb 13 '23 03:02

Matthew Plourde


The gridlines on the x axes will be aligned if you use scale_x_continuous to force ggplot to use limits you specify.

My_plot <- ggplot(data = m, aes(x = x, y = y)) + theme_bw() + 
              scale_x_continuous(limits=range(m$x))

Now, when you add the layers, the axes will share the common scaling.

like image 28
eipi10 Avatar answered Feb 13 '23 02:02

eipi10