Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving AND showing plots in rmd file

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.

like image 875
Paula Avatar asked Apr 28 '17 10:04

Paula


People also ask

How do I save a plot in a RMD file?

You want to make sure that you save images you create in your rmarkdown document. To do this automatically, and avoid writing things like ggsave(plot) or dev. off() , just create the plots in rmarkdown, and tell it you want to save the output. In the funky looking code at the top, the YAML, specify keep_md: yes .

How do I display plots in R markdown?

In RStudio, when you open a new RMarkdown file, in the editor pane, there is a cogwheel button / menu where you can choose "Chunk Output Inline". That should put the plots into the document.

How do you save a plot in RStudio?

If you are working with RStudio, the plot can be exported from menu in plot panel (lower right-pannel). It's also possible to save the graph using R codes as follow: Specify files to save your image using a function such as jpeg(), png(), svg() or pdf().

How do I save multiple plots in R?

To save multiple plots to the same page in the PDF file, we use the par() function to create a grid and then add plots to the grid. In this way, all the plots are saved on the same page of the pdf file. We use the mfrow argument to the par() function to create the desired grid.


1 Answers

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

plot(cars)

png('cars_plot.png')

plot(cars)

dev.off()
like image 112
Catherine Avatar answered Oct 25 '22 04:10

Catherine