Question

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?

Was it helpful?

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.

OTHER TIPS

You have to wrap it around print() to make it work in sweave.

Actually, while both previous answers are correct, your problem is something else.

You need to ensure that the entire code block is at the left of the page (apart from iundentation in functions). Again, I have no idea why but this causes problems for Sweave.

After ensuring that all code (and header/footer for code chunk) were at the left of the page (and adding a print statement) then your example works for me.

Incidentally, i learned today that you can create an environment around your code in sweave documents (which i wasn't aware of, and will save me much time). Good old stackoverflow, teaching you something new even when you answer a question!

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top