Search code examples
rggplot2magick

pipe ggplot2 result into 1 magick object


Is it possible to pipe the result of ggplot2 directly into magick?

Workflow that already works:

  1. I can create several plots with ggplot2 plot1, plot2, plot3 etc. results in plot1.png, plot2.png, plot3.png

  2. I can then use magick to read all the pngs and combine all the pictures into a gif.

Is it possible to do this without saving to disk first?


Solution

  • minimal example (thanks hrbrmstr and jeroen!)

    library(magick)
    library(ggplot2)
    library(purrr)
    library(dplyr)
    
    mtcars2 <- 
        mtcars %>% 
        mutate(gear = as.factor(gear))
    
    # create canvas
    frames <- image_graph(width = 300, height = 600, res = 150)
    # make a ggplot  for every gear
    walk(1:nlevels(mtcars2$gear), ~{
        xdf <- filter(mtcars2, gear == levels(gear)[.x]) # makes the   split
    gg <- 
        ggplot(data = xdf) +
        geom_point(aes(x= mpg, y = wt))
    print(gg)
    }) # ends the walk command
    
    #done with plotting
    dev.off()
    
    # animate
    image_animate(frames, 1)