Search code examples
rlatexggplot2sweave

R, Latex, Sweave, ggplot2 - change ggplot dimensions


Cuurently I am working on a R Sweave report. And I am having some difficulties with the ggplot dimensions in the sweave pdf output. My code:

\documentclass{report}

\begin{document}

demo demo demo demo demo demo demo demo demo demo demo demo 

\begin{figure}[h]
 \begin{center}
<<echo=FALSE, fig=TRUE>>=
require(ggplot2)
df <- data.frame(a= c(1:10), b = c (10:1))

ggplot(data = df, aes(a, b)) + geom_line()
@
  \caption{caption}
 \end{center}
\end{figure}

demo demo demo demo demo demo demo demo demo demo demo demo 

\end{document}

Now I want to control the plot width and height dimensions in the pdf output. actually I want to keep the height the same but make the width as the same as the text width.

Thanks for your time.


Solution

  • Have a look at the ggsave.latex() function from the AFLP package which is available on R-Forge

    install.packages("AFLP", repos="http://R-Forge.R-project.org")
    

    Then your Sweave file simplifies to this

    \documentclass{report}
    
    \begin{document}
    
    demo demo demo demo demo demo demo demo demo demo demo demo 
    
    <<echo=FALSE, results = tex>>=
    library(ggplot2)
    ggsave.latex <- AFLP:::ggsave.latex
    df <- data.frame(a= c(1:10), b = c (10:1))
    p <- ggplot(data = df, aes(a, b)) + geom_line()
    ggsave.latex(p, filename = "myplot.pdf", width = 2, height = 10, caption = "Your caption")
    @
    
    demo demo demo demo demo demo demo demo demo demo demo demo 
    
    \end{document}