Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I produce more than one file format per plot code in R?

Tags:

plot

r

image

I use Github markdown to document my data analysis with R. When I make a plot I use:

jpeg("file_name.jpg")
plot(...)
dev.off()

to save the plot as a jpeg that can then be embedded and displayed in the markdown document like this:

!(file_name.jpg)

However, I also need to make a pdf of the plot for the final publication. Currently I write the entire plot code over again with pdf("file_name.pdf") but this results in a lot of basically duplicate code.

I have tried putting the jpeg and pdf calls in sequence but then only the bottom one gets produced.

Is there a way to make the jpeg and pdf file from the same code during only one run of the code?

like image 951
DQdlM Avatar asked Jul 17 '13 18:07

DQdlM


People also ask

How do I create a multi plot pdf 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.

How do I arrange multiple Ggplots in R?

To arrange multiple ggplots on one single page, we'll use the function ggarrange()[in ggpubr], which is a wrapper around the function plot_grid() [in cowplot package]. Compared to the standard function plot_grid(), ggarange() can arrange multiple ggplots over multiple pages.

How do I combine multiple Ggplots?

Combine the plots over multiple pagesThe function ggarrange() [ggpubr] provides a convenient solution to arrange multiple ggplots over multiple pages. After specifying the arguments nrow and ncol, ggarrange()` computes automatically the number of pages required to hold the list of the plots.


2 Answers

Or you can use dev.copy:

plot(cars)
dev.copy(jpeg, "cars.jpeg")
dev.off()
dev.copy(pdf, "cars.pdf")
dev.off()
like image 66
plannapus Avatar answered Oct 21 '22 03:10

plannapus


Why not to use knitr? for example:

```{r myplot,fig.width=7, fig.height=6,dev=c('png','pdf','jpeg')}
plot(cars)
```

This will create 3 versions/files of the same plot:

  1. myplot.png
  2. myplot.jpeg
  3. myplot.pdf
like image 3
agstudy Avatar answered Oct 21 '22 03:10

agstudy