1

I starting learning Sweave today, and I am having difficulty positioning my figures correctly. I am finding that when I use the figure environment, the position of the figure doesn't correspond to its position in the document. Here is a minimal example of a .Rnw file showing with this problem:

%figure appears after both text A and text B
\documentclass[12pt]{article}

\begin{document}
\SweaveOpts{concordance=TRUE}
Text A
\begin{figure}
\begin{center}
<<fig=TRUE, echo=FALSE>>=
hist(rnorm(100))
@
\end{center}
\caption{histogram}
\label{fig:hist}
\end{figure}

Text B
\end{document}

In this example, text A and text B both appear after the figure, which is not what I would expect. Surprisingly, if I don't use the figure environment, the figure is positioned correctly:

%figure appears between text A and text B 
\documentclass[12pt]{article}

\begin{document}
\SweaveOpts{concordance=TRUE}
Text A
\begin{center}
<<fig=TRUE, echo=FALSE>>=
hist(rnorm(100))
@
\end{center}
\end{document}

Any ideas?

m0nhawk
  • 9,664
abayesed
  • 155
  • 5
    Why surprisingly? This is not a problem; it's the expected behaviour for floating objects (figure is one of such objects). Please refer to this excellent answer http://tex.stackexchange.com/a/39020/3954 by Frank Mittelbach. – Gonzalo Medina Apr 22 '13 at 01:51
  • have a look at Q2 and 3 of the faq – cmhughes Apr 22 '13 at 02:18
  • An alternative to options [!h] or [H] is do not use the figure environment at all. You still can use numbered captions using a KOMA Script class or the packages caption or capt-of that offer the \captionof command for captions outside floats (although I always prefer a well \referenced [tbp] float). – Fran Apr 22 '13 at 19:36
  • Sorry, I didn't realize I didn't actually include an option for the figure position, such as [!h], this is of course the easiest solution. – abayesed Apr 23 '13 at 14:55

0 Answers0