Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate one plot out of many when using knitr?

Tags:

r

knitr

I am using knitr with plots. I would like to rotate one of them 90 degree. For example:

\documentclass{article}

\begin{document}


<<cache=TRUE, echo=FALSE, message=FALSE, warning=FALSE, comment=NA, eval=TRUE, results=asis>>=

library("ggplot2")
library("gridExtra")

func <- function(data,x,y) {

  p1 <- ggplot(data.frame(data), aes(x = x, y = y)) + geom_point()
  p2 <- ggplot(data.frame(data), aes(x = x, y = y)) + geom_point()
  p3 <- ggplot(data.frame(data), aes(x = x, y = y)) + geom_point()
  p4 <- ggplot(data.frame(data), aes(x = x, y = y)) + geom_point()

  grid.newpage() 
    pushViewport(viewport(width = .9, height = .9,layout = grid.layout(nrow=2, ncol=2)))
    print(p1,vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
    print(p2,vp = viewport(layout.pos.row = 2, layout.pos.col = 1))
    print(p3,vp = viewport(layout.pos.row = 1, layout.pos.col = 2))
    print(p4,vp = viewport(layout.pos.row = 2, layout.pos.col = 2))

  grid.newpage() 
    pushViewport(viewport(width = .8, height = .5,layout = grid.layout(nrow=1, ncol=2)))
    print(p1,vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
    print(p2,vp = viewport(layout.pos.row = 1, layout.pos.col = 2))

}

x <- runif(20,0,1)
y <- rnorm(20)
test <- cbind(x,y)
func(test,x=test$x,y=test$y)

@    

\end{document}

I would like to rotate both the second page and the graph 90 degree. I know I can use this for one page:

\usepackage{pdflscape}
\begin{landscape}
....
\end{landscape}

But the two plots are arranged by grid.newpage() within one function. How can I achieve that? Thanks a lot!

like image 459
Autumn Avatar asked Nov 27 '12 22:11

Autumn


1 Answers

I think you can use out.extra in the chunk options:

From knitr docs: http://yihui.name/knitr/options

out.extra: (NULL; character) extra options for figures, e.g. out.extra='angle=90' in LaTeX output will rotate the figure by 90 degrees; it can be an arbitrary string, e.g. you can write multiple figure options in this option; it also applies to HTML images (extra options will be written into the tag, e.g. out.extra='style="display:block;"')

<<out.extra='angle=90', cache=TRUE, echo=FALSE, message=FALSE, warning=FALSE, comment=NA, eval=TRUE, results='asis'>>=
# ... 
@
like image 94
Brandon Bertelsen Avatar answered Oct 11 '22 17:10

Brandon Bertelsen