Search code examples
rggplot2plotfacet

Storing plots as variables in R


Hello Stack community,

For my project, I am visualizing impulse response function plots in R. I am trying to store each plot as an object in R (see PART1 of the code) in order to later append all of them in one plot (using cowplot library), as a facet chart (see PART 2 of the code). However, ultimate result of the code is an empty chart with only titles at the top.

enter image description here I believe reason for empty plot should be that R stores my plots as empty objects

enter image description here

I would greatly appreciate your help.

R code below:

#PART 1: Making IRF plots and storing them as objects

plot.1 <- plot(irf(df, impulse = "abc", response = "abc", n.ahead = 8, ortho = TRUE, runs = 1000, seed = 1))
plot.2 <- plot(irf(df, impulse = "abc", response = "def", n.ahead = 8, ortho = TRUE, runs = 1000, seed = 1))
plot.3 <- plot(irf(df, impulse = "abc", response = "ghi", n.ahead = 8, ortho = TRUE, runs = 1000, seed = 1))
plot.4 <- plot(irf(df, impulse = "abc", response = "jkl", n.ahead = 8, ortho = TRUE, runs = 1000, seed = 1))

#PART 2: making facet

library(cowplot)
plot_grid(plot.1, plot.2, plot.3, plot.4, rremove("x.text"), 
          labels = c("A", "B", "C", "D"),
          ncol = 2, nrow = 2)

Solution

  • 1) recordPlot Use recordPlot to record each plot.

    library(cowplot)
    library(irtoys)
    
    plot(irf(Scored2pl, items=c(2,3,7)), co=NA, ask = FALSE); plot1 <- recordPlot()
    plot(irf(Scored2pl), co="red", label=TRUE, ask = FALSE); plot2 <- recordPlot()
    plot(irf(Scored2pl), co="blue", label=TRUE, ask = FALSE); plot3 <- recordPlot()
    plot(irf(Scored2pl), co="green", label=TRUE, ask = FALSE); plot4 <- recordPlot()
    
    plot_grid(plot1, plot2, plot3, plot4, labels = LETTERS)
    

    screenshot

    2) formula cowplot also accepts a formula. The output is the same as above.

    library(cowplot)
    library(irtoys)
    
    plot1 <- ~ plot(irf(Scored2pl, items=c(2,3,7)), co=NA)
    plot2 <- ~ plot(irf(Scored2pl), co="red", label=TRUE)
    plot3 <- ~ plot(irf(Scored2pl), co="blue", label=TRUE)
    plot4 <- ~ plot(irf(Scored2pl), co="green", label=TRUE)
    
    plot_grid(plot1, plot2, plot3, plot4, labels = LETTERS)