r - 使用 ggplot 对齐箱线图和线图的 x 轴

标签 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 <- (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)

enter image description here

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

关于r - 使用 ggplot 对齐箱线图和线图的 x 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30402930/

相关文章:

r - r2d3 可视化中的范围 - d3.selectAll 与 svg.selectAll

javascript - 如何根据变量更改传单中的圆圈颜色?

r - 将变量传递给 ggplot2 的 aes() 中的 cut()

r - 使用 geom_sf 制作包含一组子区域的 map

r - 如何使用 ggplot2 绘制频率条形图?

mysql - 无法将 R 连接到托管在 AWS 的 Bitnami 服务器中的 mysql

r - 使用 RStudio 的 Keras 界面使神经网络训练可重现

在 lapply(.SD,...) 中为 data.table R 保留列名

r - 如何使用 ggplot2 在同一个图形上叠加多个 stat_contour 图?

r - 使用 ggplot2 在给定的 x 值处绘制数据帧的每行一行