Reputation: 143
Supposing if I have this function to print a plot in a PDF file:
generatePlot<-function(values) {
pdf(file = "foo.pdf")
barplot(values, main = "A simple example")
dev.off()
}
And then I am doing this in a "test.Rmd", parameterizing r warning=FALSE, message=FALSE, echo=FALSE
, that will output a PDF document:
tmp.values <- sample(10, 6)
generatePlot(tmp.values)
The problem is: plot just is appearing on "foo.pdf" and not on "test.pdf". In the second one, I observe only the following:
## pdf
## 2
What do I have to do for the plot to be printed in both files?
Upvotes: 3
Views: 1925
Reputation: 23909
Try the following:
---
title: "My HTML page"
output: pdf_document
---
```{r, warning=FALSE, message=FALSE, echo=FALSE}
generatePlot<-function(values) {
barplot(values, main = "A simple example")
dev.copy(pdf, "foo.pdf")
invisible(dev.off())
}
```
```{r warning=FALSE, message=FALSE, echo=F}
generatePlot(mtcars$mpg)
```
As you can see I am using dev.copy
instead to make sure that the plot is printed on the default device first and then copied to the pdf device which saves the plot at the location of the Rmd document. In order to suppress the output of dev.off()
use invisible()
.
Upvotes: 3