Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get sweave to center figures without centering code

Tags:

r

latex

sweave

One way to get sweave to center figures is to include something like the following

\begin{figure}
\begin{center}
[sweave chunk]
\end{center}
\end{figure}

However, if you want to display the code to produce the visualization, the code comes out centered. Does anyone know of a slick way to get the code to display left-justified while still making sure the figure is centered? This is problematic if you set the size of the figure to say 3x3:

<<myplot, fig=TRUE, width=3, height=3>>=
    plot(rnorm(20), rnorm(20))        
@

I need to do this more than 100 times for a project I'm working on and would prefer not to create separate chunks for the plot and the code.

like image 511
Solomon Avatar asked Jun 18 '11 21:06

Solomon


1 Answers

Maybe not exactly what you are after, but I like to keep the code I use to make the picture outside of the figure region, as I want the code in the text:

Blablabla if we run:
R CODE
We get the figure in Figure 1

You can do this by using include=false in the Sweave arguments and using the fact that if you make a picture in Sweave it calls the pdf DOCUMENTNAME-PICTURENAME.pdf. For example, in document foo.Rnw:

Blablabla if we run:
<<myplot,fig=true,include=false>>=
plot(1)
@
We get the plot in Figure \ref{myplot}

\begin{figure}
\begin{center}
\includegraphics{foo-myplot}
\end{center}
\label{myplot}
\caption{This is my plot!}
\end{figure}

This should get your code left justified in the running text and the figure wherever LaTeX places it (if you want right there).


Edit:

Running your example does get me left justified code at the same margin as normal text though:

\documentclass{article}
\usepackage{Sweave}
\begin{document}
\begin{figure}
\centering
<<myplot, fig=TRUE, width=3, height=3>>=
    plot(rnorm(20), rnorm(20))        
@
\end{figure}
\end{document}
like image 184
Sacha Epskamp Avatar answered Nov 14 '22 00:11

Sacha Epskamp