0

I'm trying to efficiently resize grobs for making publication quality plots. I'm repeatedly running into the same error in contexts where I'm using code offered in Stack Overflow answers and where that code seems to involve (I think) working with grobs that are in a list form.

Here is a self contained example, taken from what looks like a great answer to a previous stack overflow question (link at bottom):

library(grid)
library(gridExtra)
library(ggplot2)

morletPlots <- replicate(5, ggplot(), simplify = FALSE)
rawplot <- replicate(5, ggplot(), simplify = FALSE)

glets <- lapply(morletPlots, ggplotGrob)
graws <- lapply(rawplot, ggplotGrob)

rawlet <- function(raw, let, heights=c(4,1)){
  g <- rbind(let, raw)
  panels <- g$layout[grepl("panel", g$layout$name), ]
  #  g$heights <- grid:::unit.list(g$heights) # not needed
  g$heights[unique(panels$t)] <- lapply(heights, unit, "null")
  g
}

combined <- mapply(rawlet, raw = graws, let=glets, SIMPLIFY = FALSE)

grid.newpage()
grid.arrange(grobs=combined, ncol=2)

When I try to run this, I get:

Error in [<-.unit(*tmp*, unique(panels$t), value = list(4, 1)) : Value being assigned must be a unit

What am I doing wrong in trying to make this (and similar code) work?

Example taken from baptiste's answer to this question

neuropsych
  • 305
  • 3
  • 11

1 Answers1

1

Some code might have changed in time. The classes of the objects were messed up within the process. This works:

library(grid)
library(gridExtra)
library(ggplot2)

morletPlots <- replicate(5, ggplot(), simplify = FALSE)
rawplot <- replicate(5, ggplot(), simplify = FALSE)

glets <- lapply(morletPlots, gta)
graws <- lapply(rawplot, ggplotGrob)

rawlet <- function(raw, let, heights=c(4,1)){
  g      <- gtable_rbind(let, raw)
  panels <- g$layout[grepl("panel", g$layout$name), ]
  g$heights[unique(panels$t)] <- unit(heights, units = "null")
  g
}

combined <- mapply(rawlet, raw=graws, let=glets, SIMPLIFY = F)

grid.newpage()
grid.arrange(grobs=combined)

Some code might have changed in time. The classes of the objects were messed up within the process.

Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98