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?
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.
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.
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.
Or you can use dev.copy
:
plot(cars)
dev.copy(jpeg, "cars.jpeg")
dev.off()
dev.copy(pdf, "cars.pdf")
dev.off()
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With