R / Sweave: Prefixing and figure file naming - r

I am new to R and much newer to Sweave and I am experimenting with graphics. Here is a sample code:
\documentclass[a4paper]{article}
\usepackage{Sweave} %%%%%%
\SweaveOpts{eps=true}
\begin{document}
<<echo=FALSE>>=
test.frame<-data.frame(year=8:11, value= c(12050,15292,23907,33991))
#
\SweaveOpts{prefix.string=Evolution}
<<label=amount,echo=FALSE,results=hide>>=
postscript('doudou.eps',
width=6, height=7,
colormodel="cmyk",
family = "ComputerModern")
with(test.frame,plot(year, value))
dev.off()
#
\begin{figure}[htbp]
\begin{center}
\includegraphics[width=1\textwidth,angle=90]{doudou.eps}
\end{center}
\end{figure}
\end{document}
What I want to do above?
To have manual control over the EPS file that I am inserting so that I can have the \includegraphicscommand in the Sweave file itself.
And I am trying to give a proper file name to the figure: with prefix Evolution and label amount such that the EPS figure produced will be named Evolution-amount.eps.
What is going wrong?
As you can see, I am inserting a file name in the R postscript option i.e. doudou.eps . If I don't do this a file named Rplots.ps is created by R.
So my code is well ignoring the prefix and label that I want to give to my figure file.
And I am explicitly asking later on by \includegraphics to put doudou.eps.
How I want it to be?
To be able to have prefix and label as I mentioned above in the figure file name, while I still have manual control over the \includegraphics command in the Sweave file. Is this possible?
What is the use of this?
Say I am writing a paper and I have figures in different sections. So it would be nice to have something like:
\SweaveOpts{prefix.string=Paper2}
<<label=section2,echo=FALSE,results=hide>>=
and for example I specify in the postscript option: model.eps.
Then the figure would be named Paper2-section2.model.eps for example. Is that feasible?
And I would need to put this name somehow manually ?? in the \includegraphics command that follows.
Thanks a lot...
Update: 09 dec 2011.
A close solution with the help of cbeleites is:
\documentclass[fleqn, a4paper,12pt]{article}
\usepackage[latin1]{inputenx}
\usepackage[T1]{fontenc}
\usepackage{Sweave} %%%%%%
\SweaveOpts{eps=TRUE}
\begin{document}
<<echo=FALSE>>=
test.frame<-data.frame(year=8:11, value= c(12050,15292,23907,33991))
#
\SweaveOpts{prefix.string=Paper2}
<<label=section2, echo=FALSE,results=hide>>=
ps.options ( width=6, height=7, colormodel="cmyk", family = "ComputerModern")
#
<<label=section2, fig=TRUE, include = TRUE, echo=FALSE>>=
with(test.frame,plot(year, value))
#
\end{document}
On compilation I get the EPS and PDF files named Paper2-section2. This is as close as we can get I think.

You need to use a figure chunk.
<<fig=TRUE, include = FALSE>>=
with(test.frame,plot(year, value))
#
You can pass more options to the figure chunk, such as width and height.
for more advanced options, use R's postscript options:
<<>>=
ps.options (colormodel="cmyk", family = "ComputerModern")
#
if the options apply only to one figure, you'd probably be easier off without figure chunk and with manual \includegraphics. You could give the filename to the ps file as if it was produced by a Sweave figure chunk, though.
If the only reason for \includegraphics is that you want to control its options, have a look at graphicx' Gin:
\begin{figure}[htbp]
\begin{center}
\setkeys{Gin}{width=\linewidth}
<<fig=TRUE>>=
with(test.frame,plot(year, value))
#
\end{center}
\end{figure}
I thought Gin would work with the rotation as well, but it doesn't. see https://tex.stackexchange.com/a/31013 for explanation and possible solution. However, if the rotation is only because the figures appear sideways (as opposed to you wanting them to be sideways) this may be solved with correct ps settings in R (RSiteSearch () and ? postscript should help).

Related

Display a graphic in report with sweave : Just display the final report and no intermediate file

I know R well but I start in Sweave.
I produce a report under Rstudio from several scripts:
graphic.R which defined a graphic created with ggplot2 called graph_1. I want to display it in the report.
script.Rnw containing Latex and Sweave code. I call graph_1 to display my graphic.
main.R script that executes the .Rnw code and therefore produces the report.
In graphic.R
library(ggplot2)
graph_1 <- ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point(aes(color=Species, shape=Species))
In script.Rnw
\documentclass[french,12pt]{article}
\begin{document}
... no important...
\begin{figure}[h]
\begin{center}
<< fig=TRUE, echo=FALSE, height = 2.5>>=
graph_1
#
\caption{caption figure 1}
\label{graph_1}
\end{center}
\end{figure}
\end{document}
In main.R
Sweave("script.Rnw", encoding="UTF-8")
tools:::texi2dvi(file="script.tex"), pdf=TRUE)
Everything is OK : my report (.pdf) is generated in the folder. But I also have a file : 'script-001.pdf' containing my graphic which is added in the same folder.
I would like only the final report and not the intermediate file : so not the file 'script-001.pdf'.
Somebody know if it is possible ?
Thank you,
The figure file is required so that LaTeX can include it. But you can delete it safely after running Sweave and LaTeX.
I don't like my working directory to be littered with intermediate PDFs, too. So I have them end up in a folder called figures. With Sweave you can accomplish this by setting a suitable prefix:
\SweaveOpts{prefix.string=figures/fig}
You also need to create the figure folder yourself for it to work.
And a personal recommendation: You may want to have a look at knitr – it's a more powerful modern version of Sweave – in my opinion.

R Sweave: put the whole code of the .Rnw file in Appendix?

I just found this awesome technique to put the code used in the .Rmd file in the appendix (of that same file).
However, I am using R Sweave and not R Markdown and I would like to know if there exists a similar way to put all the code at the end in a unique chunk. The code to do that in Markdown does not work in Sweave. I precise that, unlike this post, I do not have a separate .R file where the calculations are made. Everything is done in the .Rnw file.
Does anybody know how to do it?
Edit : a reproducible example
\documentclass[11pt, twocolumn]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\begin{document}
\SweaveOpts{concordance=TRUE}
<<reg2, echo=FALSE, print=FALSE>>=
head(mtcars)
#
<<reg3, echo=FALSE, print=FALSE>>=
head(iris)
#
\section*{Appendix}
% the place where I could like to put the whole code
\end{document}
This chunk works to include the code:
<<echo=FALSE, eval=TRUE>>=
filename <- tempfile(fileext=".R")
Stangle("test.Rnw", output = filename, quiet = TRUE)
cat(readLines(filename), sep = "\n")
#
When I include that in your example file, I see this:
I think it's possible to modify the format a bit; see ?Rtangle for some details. Similar things are possible with knitr, but it's more flexible. I suspect the best method would be similar to the one you found for RMarkdown.

Is it possible to give a figure/plot a label in Sweave? [duplicate]

I can't get R/KnitR to create the LaTeX \label{} statement for a figure. The manual seems to indicate that a \label{} statement will be created by concatenating the string in fig.lp ("fig:" by default) with the label for the R-code chunk. I haven't been able to get this to work, however. No \label{} statement is created for the first figure created by knitting the MWE below. The second figure has it's label added with a workaround that I just discovered, putting the R chunk in a figure environment, and putting the \label tag after or inside the \caption tag.
\documentclass[12pt, english, oneside]{amsart}
\begin{document}
Figure \ref{fig:plot} doesn't have it's label.
<<plot>>=
plot(x=0, y=0)
#
Figure \ref{fig:plot2} has its label.
\begin{figure}
\caption{\label{fig:plot2}}
<<>>=
plot(x=1,y=1)
#
\end{figure}
\end{document}
Okay, I've found a workaround by putting the R chunk in a \begin{figure} . . .\end{figure} environment in LaTeX. I can create the label in that same environment. Still, I'd like to understand how Yihui intends for this to be handled with KnitR.
You need to set fig.cap = '' (or whatever you wish) to ensure that a figure environment is used in the latex document. (you may have noticed that the \begin{figure} ... \end{figure} is missing along with the \label{} component
eg
\documentclass[12pt, english, oneside]{amsart}
\begin{document}
See Figure \ref{fig:plot}.
<<plot, fig.lp="fig:", fig.cap = ''>>=
plot(x=0, y=0)
#
\end{document}
I would agree that the description from the website is less than clear as to this being necessary.
fig.env: ('figure') the LaTeX environment for figures, e.g. set fig.env='marginfigure' to get \begin{marginfigure}
fig.cap: (NULL; character) figure caption to be used in a figure environment in LaTeX (in \caption{}); if NULL or NA, it will be
ignored, otherwise a figure environment will be used for the plots in
the chunk (output in \begin{figure} and \end{figure})
Although the graphics manual is clear, and the reasoning makes sense
Figure Caption
If the chunk option fig.cap is not NULL or NA, the
plots will be put in a figure environment when the output format is
LATEX, and this option is used to write a caption in this environment
using \caption{}. The other two related options are fig.scap and
fig.lp which set the short caption and a prefix string for the figure
label. The default short caption is extracted from the caption by
truncating it at the first period or colon or semi-colon. The label is
a combination of fig.lp and the chunk label. Because figure is a float
environment, it can float away from the chunk output to other places
such as the top or bottom of a page when the TEX document is compiled.
If you were wishing to replicate a R session output, you wouldn't want the figures to float away from the line of code which defines how they were created.

R knitr - include graphics (ggplot2 object rendered in R code ) directly in a defined place

I am making my first steps with knitr, trying to generate a raport. In the raport, I include R code which generates a ggplot2 object that I want to be included directly below some text. To make it more detailed, the graphic is a pair of two separated plots, which I want to be placed parallelly, one next to another.
So far, I have been dealing with by using the R code: producing and saving a .pdf picture, and then reading this picture from file and including it in the report by \includegraphics command. However, it is no more a solution for me - I want the plot to be generated simultaneously with the report by the R code (in particular: not to be saved anywhere as a .pdf)
However, the code I tried to use did not work properly - it generates the 2 plots, but they are however:
1) incorrectly placed - 2 pages below (which is even not the end of the document!)
2) I don't know how to place them in one row, with the defined size.
Please be of some help! Thank you in advance!! [below my not working porperly R code]
\textit{Pic 1 title} Some pic description
\begin{figure}[h]
\subfigure[pic1 name]{
<<echo = F, eval = T, message=F, fig=TRUE>>=
# a function returning a ggplot2 object (with a proper parameters instead of "...")
plot.matrix.from.file(...)
#
% below there is a fragment of the code I used before (which includes a graphics directly from a .pdf file)
%\includegraphics[scale=0.4]{data/simulated.data/obs_pred_mean_Gini_r.pdf}
\label{pic1 label}
}
\subfigure[pic2 name]{
<<echo = F, eval = T, message=F>>=
# a function returning a ggplot2 object (with a proper parameters instead of "...")
plot.matrix.from.file(...)
#
% below there is a fragment of the code I used before (which includes a graphics directly from a .pdf file)
%\includegraphics[scale=0.4]{data/simulated.data/obs_pred_var_Gini_r.pdf}
\label{pic2 label}
}
\caption{caption for the pair of plots}
\end{figure}
I do not see any problems using the subcaption package. See example 104.
\documentclass{article}
\usepackage{subcaption}
\begin{document}
You can include sub-figures using the \textbf{subcaption} package. For example,
Figure \ref{fig:test} contains \ref{fig:test-a} and \ref{fig:test-b}.
\begin{figure}
\begin{subfigure}{.5\textwidth}
<<test-a, echo=FALSE, results='asis', fig.width=5, fig.height=5>>=
plot(1:10)
#
\caption{This is Figure a. \label{fig:test-a}}
\end{subfigure}
\begin{subfigure}{.5\textwidth}
<<test-b, echo=FALSE, results='asis', fig.width=5, fig.height=5>>=
plot(rnorm(100))
#
\caption{This is Figure b. \label{fig:test-b}}
\end{subfigure}
\caption{This figure contains two subfigures. \label{fig:test}}
\end{figure}
\end{document}
Output as expected:

figure* environment in twocolumn knitr/Sweave document

Sounds like it should be a common problem, but I didn't find an obvious trick.
Consider the knitr Rnw file below,
\documentclass[twocolumn, 12pt]{article}
\usepackage{graphicx}
\begin{document}
%\SweaveOpts{dev=pdf, fig.align=center}
\begin{figure*}
<<aaa, fig.width=8, fig.height=5, fig.show=hold>>=
plot(1,1)
#
\end{figure*}
\end{document}
I would like this wide figure to span two columns, using a {figure*} LaTeX environment. Is there a hook for that?
EDIT: wrapping the chunk in figure* gives the following output.
Two facts:
knitr makes everything accessible for you, so LaTeX tricks are often unnecessary;
there is a chunk hook with which you can wrap your chunk results;
A simple-minded solutions is:
knit_hooks$set(chunk = function(x, options) {
sprintf('\\begin{figure*}\n%s\n\\end{figure*}', x)
})
I leave the rest of work to you to take care of more details in options (e.g. when options$fig.keep == 'none', you should not wrap the output in figure*). You may want to see how the default chunk hook for LaTeX is defined in knitr to know better how the chunk hook works.
However, in this case, I tend to write the LaTeX code by myself in the document instead of automatically creating it. After you have got figure*, you may start to think about \caption{} and \label{} (not hard, but I still want to see them in LaTeX).
Not sure about how knitr but for Sweave (and basic latex) there is in fact a trick: have the R code produce a pdf file, and then use standard \includegraphics to pull it in.
So with this:
\documentclass[twocolumn, 12pt]{article}
\usepackage{graphicx}
\begin{document}
%\SweaveOpts{dev=pdf}
<<aaa,fig=FALSE,print=FALSE,echo=FALSE>>=
pdf("mychart.pdf", width=6, height=3)
set.seed(42)
plot(cumsum(rnorm(100)), type='l', main="yet another random walk")
invisible(dev.off())
#
\begin{figure*}
\includegraphics{mychart.pdf}
\end{figure*}
\end{document}
I got the document below (which I then converted from pdf to png):
I also had a similar problem while preparing a figure that should span two columns in a IEEE two-column conference paper.
Setting the chunk hook caused some strange error in my setup.
Even this simple hook: knit_hooks$set(chunk = function(x, options) x)
But after looking into knitr::opts_chunk$get(), I realized that simply setting fig.env="figure*" solves the problem in an elegant way.
Here is how my chunk looks like in an Rnw file:
<<fig1, fig.width=18, fig.height=6, fig.env="figure*">>=
#

Resources