我试图使用ggplot在一个窗口框架中对齐条形图和线图的x轴.这是我试图用它做的假数据.
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)
谢谢您的帮助.
@ eipi10回答了这种特殊情况,但一般来说你还需要均衡绘图宽度.例如,如果其中一个图上的y标签占用的空间大于另一个图上的y标签,即使您在每个图上使用相同的轴,它们也不会在传递给时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)

在这种情况下,您必须均衡绘图宽度:
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)
