R 使用ggplot对齐方框图和线条图的x轴

R 使用ggplot对齐方框图和线条图的x轴,r,ggplot2,R,Ggplot2,我正在尝试使用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 <- (g

我正在尝试使用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)
库(ggplot2)
图书馆(gridExtra)

m如果使用
scale\u x\u continuous
强制
ggplot
使用指定的限制,则x轴上的网格线将对齐

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

My_plot@eipi10回答了这种特殊情况,但一般来说,您还需要均衡打印宽度。例如,如果其中一个图上的y标签比另一个图上的y标签占用更多空间,即使在每个图上使用相同的轴,它们在传递到
网格时也不会对齐。排列

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)

axis这个方法是否也适用于使用高度对齐每个绘图的y轴?我想。“试试看?”杰克·康威:是的,是的。但请参见以下答案,以获得更简洁的方法:
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)