Search code examples
rr-forestplot

How to save a plot created with forestplot package in R?


I have created a forest plot using the forestplot package in R as follows:

own <- fpTxtGp(ticks = gpar(cex = 0.65), xlab = gpar(fontsize = 16))

xticks <- seq(from = -0.25, to = 1, by = 0.25)

fn <- local({
  i = 0
  no_lines <- sum(!is.na(forest$mean))
  b_clrs = colorRampPalette(colors=c("#21538A", "#21538A", "#A2B6D3", "#A2B6D3", "#DAE0EC"))(no_lines)

  function(..., clr.marker){
    i <<- i + 1
    fpDrawCircleCI(..., clr.marker = b_clrs[i])
  }
})

fplot <- forestplot::forestplot(text, 
                                fn.ci_norm = fn,
                                lower = forest$low, 
                                upper = forest$high, 
                                mean = forest$mean, 
                                is.summary = c(TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE),
                                xlab = "SPI-CY risk score difference (SD)",
                                col = fpColors(line = "darkgrey", summary = "#DAE0EC", zero = "black"), 
                                vertices = TRUE, 
                                grid = TRUE,
                                boxsize = .35,
                                txt_gp = own,
                                xticks = xticks,
                                lwd.zero = 1.25
                                ) 

I would like to save the plot directly from my R notebook. I typically save plots with ggsave, but the forest plot is a grid object, so this did not work:

ggsave("forestplot.png", height = 5, width = 7, dpi = 600)

I have tried to save it with pdf(), but this also did not work directly from my notebook. Any suggestions are welcome.


Solution

  • To save the plot directly from your R notebook (I added the plot initialization thanks to user2554330's comment):

    # initialize plot
    png("forestplot.png", width=480, height=480)
    
    # make plot
    fplot
    
    # save plot
    dev.copy(png, "forestplot.png")
    dev.off()