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.
How can I plot these aligned? Thanks