'R - Error when using rbind on two ggplotGrob objects
I'm trying to follow this example of combining two plots (link and code below) using the gtable package. I've tried running the code to see what the output looks like, but I'm getting an error on the following line:
g <- rbind(g1, g2, size="first") # stack the two plots
**Error: x and y must have the same number of columns**
I've looked at g1 and g2 individually and they both look like they have identical columns and column names. Can anyone see what the issue is?
https://github.com/tidyverse/ggplot2/wiki/Align-two-plots-on-a-page
library(ggplot2)
x <- seq(1992, 2002, by=2)
d1 <- data.frame(x=x, y=rnorm(length(x)))
xy <- expand.grid(x=x, y=x)
d2 <- data.frame(x=xy$x, y=xy$y, z= jitter(xy$x + xy$y))
p1 <- ggplot(data = d1, mapping = aes(x = x, y = y)) +
geom_line(stat = "identity")
p2 <- ggplot(data = d2, mapping = aes(x=x, y=y, fill=z)) +
geom_tile()
## convert plots to gtable objects
library(gtable)
library(grid) # low-level grid functions are required
g1 <- ggplotGrob(p1)
g1 <- gtable_add_cols(g1, unit(0,"mm")) # add a column for missing legend
g2 <- ggplotGrob(p2)
g <- rbind(g1, g2, size="first") # stack the two plots
g$widths <- unit.pmax(g1$widths, g2$widths) # use the largest widths
# center the legend vertically
g$layout[grepl("guide", g$layout$name),c("t","b")] <- c(1,nrow(g))
grid.newpage()
grid.draw(g)
Solution 1:[1]
There is an issue in g1$widths und g2$widths which differ in length, hence the error. You could run unit.pmax() right before calling rbind. Is the result as desired?
## convert plots to gtable objects
library(gtable)
library(grid) # low-level grid functions are required
g1 <- ggplotGrob(p1)
g1 <- gtable_add_cols(g1, unit(0,"mm")) # add a column for missing legend
g2 <- ggplotGrob(p2)#
# set the same widths for both blots
g1$widths <- unit.pmax(g1$widths, g2$widths)
g2$widths <- unit.pmax(g1$widths, g2$widths)
# stack them afterwards
g <- rbind(g1, g2, size="first") # stack the two plots
g$layout[grepl("guide", g$layout$name),c("t","b")] <- c(1,nrow(g))
grid.newpage()
grid.draw(g)
Solution 2:[2]
I solved it by changing the number of missing legend added to g1:
g1 <- gtable_add_cols(g1, unit(0,"mm")) # add a column for missing legend
Typing "g1" and "g2" in console, the information, including the dimension, of g1 and g2 will be shown. Then you can determine which one need more legends to be the same as the other one.
You probably had different ggplot objects than the example. Adding one column for missing legend to g1 is specific to the ggplot object of the example.
Good luck!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mnist |
| Solution 2 |
