plotting a list of grobs

2020-07-18 08:01发布

DISCLOSURE: I'm not sure how to make a reproducible example for this question.

I'm trying to plot a list of grobs using the gridExtra package.

I have some code that looks like this:

## Make Graphic Objects for Spec and raw traces
for (i in 1:length(morletPlots)){
  gridplots_Spec[[i]]=ggplotGrob(morletPlots[[i]])
  gridplots_Raw[[i]]=ggplotGrob(rawPlot[[i]])
  gridplots_Raw[[i]]$widths=gridplots_Spec[[i]]$widths
}
names(gridplots_Spec)=names(morletPlots)
names(gridplots_Raw)=names(rawPlot)

## Combine spec and Raw traces
g=list()
for (i in 1:length(rawPlot)){
    g[[i]]=arrangeGrob(gridplots_Spec[i],gridplots_Raw[i],heights=c(4/5,1/5))
}

numPlots = as.numeric(length(g))

##Plot both
for (i in 1:numPlots){

  grid.draw(g[i],ncol=2)
}

Let me walk through the code.

morletPlots = a list of ggplots

rawplot = A list of ggplots

gridplots_spec and gridplots_Raw = list of grobs from the ggplots made above.

g = a list of the two grobs above combined so combining gridplots_spec[1] and gridplots_raw[1] so on and so on for the length of the list.

now my goal would be two plot all of those into 2 columns. But whenever I pass the gridplots_spec[i] through the grid.draw loop I get an error:

Error in UseMethod("grid.draw") : no applicable method for 'grid.draw' applied to an object of class "list"

I can't unlist it becasue it just turns into a long character vector. any ideas?

If it's absolutely crucial I can spend the time to make an reproducible example but I'm more likely just missing a simple step.

标签: r gridextra grob
1条回答
Juvenile、少年°
2楼-- · 2020-07-18 08:42

Here's my interpretation of your script, if it's not the intended result you may want to use some bits and pieces to make your question reproducible.

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)

enter image description here

Edit I can't resist this mischievous hack to colour the plots for illustration; feel free to ignore it.

palette(RColorBrewer::brewer.pal(8, "Pastel1"))
ggplot.numeric = function(i) ggplot2::ggplot() + 
  theme(panel.background=element_rect(fill=i))

morletPlots <- lapply(1:5, ggplot)
rawplot <- lapply(1:5, ggplot)

enter image description here

查看更多
登录 后发表回答