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.

Community
  • 1
  • 1
Paula
  • 171
  • 1
  • 1
  • 5
  • have you tried to just run the `plot(cars)` function outside your dev environment? – Sarina Apr 28 '17 at 10:29
  • also this might help you http://stackoverflow.com/questions/32083106/change-where-rmarkdown-saves-images-generated-by-r-code – Sarina Apr 28 '17 at 10:32
  • 2
    Possible duplicate of [knitr: include figures in report \*and\* output figures to separate files](http://stackoverflow.com/questions/27992239/knitr-include-figures-in-report-and-output-figures-to-separate-files) – Sarina Apr 28 '17 at 10:35
  • yes, duplicate. add Use the option `self_contained: no` in your rmd header and the files will be available in a separate folder. – YCR Apr 28 '17 at 10:48

1 Answers1

1

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

plot(cars)

png('cars_plot.png')

plot(cars)

dev.off()
Dharman
  • 30,962
  • 25
  • 85
  • 135
Catherine
  • 119
  • 1
  • 8
  • 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 '20 at 10:30