Home > database >  How to plot an R graph within latex code in Rmarkdown pdf document
How to plot an R graph within latex code in Rmarkdown pdf document

Time:10-19

Trivial but annoying issue with Rmarkdown. I am trying to display landscape and portrait pages within the same pdf document from Rmarkdown.

I searched different solutions and decided to stick to the latex option (R chunk inside LaTeX in an rmarkdown document). However, even with that option I cannot manage to put R code within latex commands.

---
title: ""
header-includes:
- \usepackage{lscape}
- \newcommand{\blandscape}{\begin{landscape}}
- \newcommand{\elandscape}{\end{landscape}}
output: pdf_document
---


\newpage
\blandscape

```{r}
plot(1,1)
```
\elandscape

\newpage
More portrait
```{r}
summary(cars)
```

I got an error:

output file: hello.knit.md

! LaTeX Error: \begin{landscape} on input line 113 ended by \end{document}.

Error: LaTeX failed to compile hello.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See hello.log for more info.
Execution halted

while the following code is working:

---
title: ""
header-includes:
- \usepackage{lscape}
- \newcommand{\blandscape}{\begin{landscape}}
- \newcommand{\elandscape}{\end{landscape}}
output: pdf_document
---


\newpage
\blandscape

```{r}
1 1
```
\elandscape

\newpage
More portrait
```{r}
summary(cars)
```

I have no idea why :D

Does someone have one ?

CodePudding user response:

Instead of defining new commands, you can directly use the underlying commands of an environment:

---
title: ""
header-includes:
- \usepackage{lscape}
output: pdf_document
---


\newpage
\landscape

```{r}
plot(1,1)
```
\endlandscape

\newpage
More portrait
```{r}
summary(cars)
```
  • Related