Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201977

Prepend a ggplot2 object to a list of plots

$
0
0

Suppose I have a list of plots plotlist and I want to call patchwork::wrap_plots(plotlist).

I also want to prepend one more plot to the beginning of the list.

Let's start with a list that has 2 plots:

library(ggplot2)
library(patchwork)

cols <- c("mpg", "hp")

plot_col <- function(this_col) {
  ggplot(mtcars) +
    aes_string("wt", this_col) +
    geom_point()
}

plotlist <- lapply(cols, plot_col)

This works:

res <- wrap_plots(plotlist)

But wait, I have one more plot.

p <- plot_col("qsec")

Can I prepend the new plot p to plotlist?

None of these approaches work: c(), list(), purrr::prepend()

newlist <- c(p, plotlist)
res <- wrap_plots(newlist)
#> Error: Only know how to add ggplots and/or grobs
newlist <- list(p, plotlist)
res <- wrap_plots(newlist)
#> Error: Only know how to add ggplots and/or grobs
newlist <- purrr::prepend(plotlist, p)
res <- wrap_plots(newlist)
#> Error: Only know how to add ggplots and/or grobs

Viewing all articles
Browse latest Browse all 201977

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>