David Johnson
David Johnson

Reputation: 439

Aligning multiple plots using ggplot and gtable

I have created two plots using ggplot2 that I would like to display simultaneously using gtable. I'm having two issues. The first is that I want the panel size to match across the two plots. I've accomplished this using gtable. The second issue is that I want the first plot to span three times as much width as the second plot. I can't seem to figure out how to do this while matching the panel size using the bind() function in ggtable.

Reproducible code is provided below.

library(ggplot2)
library(gtable)

set.seed(2345)

mean1 <- runif(8, 700, 1000)
low1 <- mean1 - 100
high1 <- mean1 + 100
names1 <- paste0("really long name", 1:length(mean1))
df1 <- data.frame(mean = mean1,
  low = low1,
  high = high1,
  names = names1)

mean2 <- runif(2, 700, 1000)
low2 <- mean2 - 100
high2 <- mean2 + 100
names2 <- paste0("name", 1:length(mean2))
df2 <- data.frame(mean = mean2,
  low = low2,
  high = high2,
  names = names2)

plot1 <- ggplot(df1, aes(x = names, y = mean)) + 
  geom_errorbar(aes(ymin = low, ymax = high), width = 0) +
  geom_point() +
  scale_y_continuous(limits = c(.95*min(df1$low), 1.05*max(df1$high))) +
  xlab("") + 
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

plot2 <- ggplot(df2, aes(x = names, y = mean)) + 
  geom_errorbar(aes(ymin = low, ymax = high), width = 0) +
  geom_point() +
  scale_y_continuous(limits = c(.95*min(df1$low), 1.05*max(df1$high))) +
  xlab("") + 
  theme(axis.text.x = element_text(angle = 0, hjust = .5))

grob1 <- ggplotGrob(plot1) #Convert to gtable 
grob2 <- ggplotGrob(plot2) #Convert to gtable

grob <- cbind(grob1, grob2, size = "first") #Bind rt data

title <- textGrob("Title", gp = gpar(fontsize = 12)) #Add title
grob <- gtable_add_rows(
  grob, #gtable object
  heights = grobHeight(title) + padding, #height for new row
  pos = 0 #0 adds on top
)
grob <- gtable_add_grob(
  grob, #gtable object
  title, #grob to be added
  t = 1, l = 1, r = ncol(sG) #top, left, and right (18) extent of grob
)

grid.newpage()
grid.draw(grob)

enter image description here

As you can see, the panel sizes match, but plot 1 (left) and plot 2 (right) are the same width. I would like to merge these two so that plot 1 is three times wider than plot 2. I also want to add a title above the two, which I've done in the code provided.

Upvotes: 3

Views: 930

Answers (1)

pogibas
pogibas

Reputation: 28319

With egg package and ggarrange function you can do everything with one code line:

egg::ggarrange(plot1, plot2, ncol = 2, top = "foo", widths = c(3, 1))

enter image description here

Upvotes: 2

Related Questions