Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I produce a plot in landscape [rotated by 90 degrees] orientation in knitr?

Tags:

r

knitr

The following knitr code give me the plot below -- how do I plot it in a landscape orientation?

```{r}
rm(list=ls())
library(tree)
set.seed(1111)
x1<-runif(100)
x2<-rnorm(100,mean=.3)
x3<-runif(100)
d1<-x1>0.5
d2<-x2>0.7
d3<-x3<0.2
y<-ifelse(d1,1,ifelse(d2,2,ifelse(d3,3,4)))
df<-data.frame(x1,x2,x3,y)
tr<-tree(y~.,data=df)
plot(tr)
text(tr)
```

enter image description here

like image 237
user975917 Avatar asked Jan 31 '26 12:01

user975917


1 Answers

If your want a pdf/LaTeX output it is quite easy with out.extra='angle=90' chunk argument :

---
title: "Rotation test"
output: pdf_document
---

```{r, out.extra='angle=90'}
rm(list=ls())
library(tree)
set.seed(1111)
x1<-runif(100)
x2<-rnorm(100,mean=.3)
x3<-runif(100)
d1<-x1>0.5
d2<-x2>0.7
d3<-x3<0.2
y<-ifelse(d1,1,ifelse(d2,2,ifelse(d3,3,4)))
df<-data.frame(x1,x2,x3,y)
tr<-tree(y~.,data=df)
plot(tr)
text(tr)
```

In some circumnstances it is better to keep the graph as it but to rotate just one page in landscape format within you document. You need pdflscape LaTeX package for this (included for example in the texlive-latex-base package in Ubuntu as "oberdiek").

In the following example the graph is extended to occupy a full A4 page in landscape format. NB : you must specify fig.align='center' to make it work.

---
title: "Rotation test"
output: pdf_document
header-includes:
      - \usepackage{pdflscape}
---

```{r}
rm(list=ls())
library(tree)
set.seed(1111)
x1<-runif(100)
x2<-rnorm(100,mean=.3)
x3<-runif(100)
d1<-x1>0.5
d2<-x2>0.7
d3<-x3<0.2
y<-ifelse(d1,1,ifelse(d2,2,ifelse(d3,3,4)))
df<-data.frame(x1,x2,x3,y)
tr<-tree(y~.,data=df)
```

\newpage

\begin{landscape}

```{r fig.align='center', fig.width = 27/2.54, fig.height = 19/2.54}
plot(tr)
text(tr)
```
\end{landscape}

```{r}
summary(tr)
```
like image 93
Gilles Avatar answered Feb 02 '26 03:02

Gilles



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!