0

I wrote a simple plotting routine.

x <- c(1,2,3,4)
output_file <- "test_plot.png"

png(output_file, units="cm", width = 12, height = 20, res=300)
plot(x, c(2,2,2,2))
dev.off()  # <- plot is saved to disk

Now I moved the routine into a function. When I call the function, no error is thrown but the plot is not save to disk. Why is this the case and how can I circumvent it?

create_plot <- function(x, output_file){
    png(output_file, units="cm", width = 12, height = 20, res=300)
    plot(x, c(2,2,2,2))
    dev.off()
}

create_plot(x, output_file)  # <- plot is not saved to disk?
Molitoris
  • 935
  • 1
  • 9
  • 31
  • 1
    Does it work if you put a `print()` around your `plot`? – Bas Jul 07 '20 at 07:17
  • Yes! This did the trick. Can you explain my why I need to print the plot in the function but not outside? – Molitoris Jul 07 '20 at 07:19
  • 1
    Did you run this exact code to test? Because it works fine for me. I'm guessing that in your actual use case you are trying to plot some other type of object that creates a lattice or ggplot object. Those values need to be `print()`ed in order to be drawn. See [R FAQ 7.22](https://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-do-lattice_002ftrellis-graphics-not-work_003f) – MrFlick Jul 07 '20 at 07:28
  • 1
    The reason why the `print()` is necessary for those types of objects is explained [in this SO answer](https://stackoverflow.com/questions/6675066/ggplots-qplot-does-not-execute-on-sourcing/6675610#6675610). – Bas Jul 07 '20 at 07:30

0 Answers0