Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing graph to a PDF file apart and a R Markdown output at same time

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?

like image 938
Nelson A. Morais Avatar asked Feb 01 '26 18:02

Nelson A. Morais


1 Answers

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().

like image 98
Martin Schmelzer Avatar answered Feb 04 '26 07:02

Martin Schmelzer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!