DQdlM
DQdlM

Reputation: 10254

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

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?

Upvotes: 5

Views: 132

Answers (3)

Ben Bolker
Ben Bolker

Reputation: 226332

@agstudy's answer is clever. The canonical answer, I think, is that if you have a lot of duplicate code you can make a little utility function and run it twice:

tmpplotfun <- function() { ... lots of plot code ... }
pdf(...)
tmpplotfun()
dev.off()
jpeg(...)
tmpplotfun()
dev.off()

You could even abstract this further:

plot_twice <- function(plotfun,...) {
   pdf(...)
   plotfun()
   dev.off()
   jpeg(...)
   plotfun()
   dev.off()
}
plot_twice(tmpplotfun)

... with a little more ingenuity you could replicate what knitr is already doing ...

Upvotes: 3

plannapus
plannapus

Reputation: 18749

Or you can use dev.copy:

plot(cars)
dev.copy(jpeg, "cars.jpeg")
dev.off()
dev.copy(pdf, "cars.pdf")
dev.off()

Upvotes: 5

agstudy
agstudy

Reputation: 121578

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

Upvotes: 3

Related Questions