6

I'm working on a rather long code using R markdown, divided into chunks. Plot appear under the appropriate chunk. I'd like to keep this behaviour, but additionally I want to save them to a specified folder. I've tried different methods listed here How to save a plot as image on the disk? (and elsewhere on the Internet), but nothing seems to work.
My reproducible example:

png('cars_plot.png')
plot(cars)
dev.off()

This code saves the plot, but doesn't show it (it only returns "null device 1"). I've also tried dev.print and dev.copy, with the same result.
Thank you in advance! Clarification: I run my chunks one by one, I don't want to convert my results to pdf/html yet. So knitr: include figures in report *and* output figures to separate files or change where rmarkdown saves images generated by r code don't answer my question.

4

1 Answer 1

1

You can always graph it twice in the same markdown chunk, like this:

plot(cars)

png('cars_plot.png')

plot(cars)

dev.off()
1
  • One may want to use either dev.off() -> . (. as kind of /dev/null variable similar to _ in Python/Prolog) or invisible(dev.off()) to suppress an output from the command.
    – Velda
    May 19, 2020 at 10:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.