我正在尝试使用 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 标签比另一个图占用更多空间,即使您在每个图上使用相同的轴,它们在传递给 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)
关于r - 使用 ggplot 对齐箱线图和线图的 x 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30402930/