Search code examples
rggplot2sweaveliterate-programming

sweave and ggplot2: no pdfs generated at all


I am trying create a sweave report that contains some graphics done with ggplot2. Though I am looking for some environment for the long run – I just use a simple .Rnw file here that only contains the code and the plot

 \documentclass[a4paper]{article}
 \SweaveOpts{echo=FALSE}
 \usepackage{a4wide}

  \begin{document}

  \begin{figure}[htbp]
  \begin{center}
 <<>>=
 library(ggplot2)
 x=rnorm(100)
 qplot(x)

 @
 \caption{My Graph}
 \end{center}
  \end{figure}
\end{document}

Unfortunately the graph is not created, I only get a corrupted .pdf and .eps file. Though I get a nice .tex file that appears to work except for the graphics. I use the following basic code to create it:

 Sweave("myfile.Rnw")

I just found some older post on the web that were discussing problems with transparency and sweave / ggplot2 but nothing that could have helped. I also tried the relaxed package, which did not help either. Btw, is there any news on decumar package?


Solution

  • qplot() produces objects, not a graphic output. It might seem like it does when you run it, but that's because without assignment, R is automatically printing the output of qplot(). To integrate it into Sweave, either wrap print() around qplot(), or assign the output of qplot() to something, then wrap that in print().

    ...
    <<fig = T, echo = F>>=
     library(ggplot2)
     x=rnorm(100)
     p <- qplot(x)
     print(p)
    @
    ...
    

    That should work. I use ggplot2 graphics in my sweave docs all the time.