1
votes

I have some data that I want to plot. I want the three plots laid out horizontally and aligned with each other. However, because some plots will have axes on the top of the plot area, I can't get the y-axes to align.

density <- rnorm(50, 0.8, 0.3)
carbonate <- rnorm(50, 75, 18)
org_per <- rnorm(50, 0.9, 1.1)
Depth_decomp <- seq(1,151,3)
Age <- seq(0,5600, 112)
df <- data.frame(cbind(density, carbonate, org_per, Depth_comp, Age))

I have plotted the data using ggplot2

library(ggplot2)
library(data.table)
library(grid)
library(gridExtra)
library(gtable)

p1 <- ggplot(df[,c(1,4)], aes(x=density, y=Depth_decomp)) + 
  theme_bw() + geom_path() + 
  labs(x=bquote('Density'~(gDWcm^-3)), y='Depth (cm)') +
  scale_y_reverse()+
  theme(axis.line=element_line(),
        axis.line.y = element_line(),
        panel.background= element_blank(),
        panel.border = element_blank())

p2 <- ggplot(df[,c(2,4)], aes(x=carbonate, y=Depth_decomp)) + 
  theme_bw() + geom_path() +
  labs(x=expression(CaCO[3]*" (%)"), y=NULL) +
  scale_x_continuous(position="top") +
  scale_y_reverse(breaks=NULL)+
  theme(axis.line=element_line(),
        panel.background= element_blank(),
        panel.border = element_blank())

p3 <- ggplot(df[,c(3,5)], aes(x=org_per, y=Age)) + 
  theme_bw() + geom_path() +
  labs(x="Organic matter (%)", y = "Ages (Cal yr BP)")+
  scale_y_reverse(position="right",
                  breaks =seq(0,6000, by=1000))+ 
  scale_x_continuous() +
  theme(axis.line=element_line(),
        panel.background= element_blank(),
        panel.border = element_blank())

gt1 <- ggplotGrob(p1)
gt2 <- ggplotGrob(p2)
gt3 <- ggplotGrob(p3)
newWidth = unit.pmax(gt1$widths[2:3], gt2$widths[2:3], gt3$widths[2:3])
gt1$widths[2:3] = as.list(newWidth)
gt2$widths[2:3] = as.list(newWidth)
gt3$widths[2:3] = as.list(newWidth)
gt = gtable(widths = unit(c(1, 1, 1, .3), "null"), height = unit(1, "null"))
gt <- gtable_add_grob(gt, gt1, 1, 1)
gt <- gtable_add_grob(gt, gt2, 1, 2)
gt <- gtable_add_grob(gt, gt3, 1, 3)
grid.newpage()
grid.draw(gt)

This produces the following graphs, which are not aligned by the y-axes.

enter image description here

How can I plot these aligned? Thanks

1

1 Answers

1
votes

Is this what you're looking for? See also this answer

library(ggplot2)

set.seed(12345)
density <- rnorm(50, 0.8, 0.3)
carbonate <- rnorm(50, 75, 18)
org_per <- rnorm(50, 0.9, 1.1)
Depth_decomp <- seq(1,151,3)
Age <- seq(0,5600, 112)
df <- data.frame(cbind(density, carbonate, org_per, Depth_decomp, Age))

Using patchwork package

library(patchwork)
p1 | p2 | p3

Using egg package

library(egg)
ggarrange(p1, p2, p3,
          ncol = 3)

Using cowplot package

library(cowplot)
plot_grid(p1, p2, p3,
          ncol = 3,
          align = 'h',
          axis = 'tb')

Created on 2018-09-06 by the reprex package (v0.2.0.9000).