Align x axes of box plot and line plot using ggplo

2019-05-06 15:03发布

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.

标签: r ggplot2
2条回答
放我归山
2楼-- · 2019-05-06 15:28

@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

查看更多
小情绪 Triste *
3楼-- · 2019-05-06 15:28

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.

查看更多
登录 后发表回答