Consider the following code in Rmarkdown, which produces a graph as below:
\begin{figure}
\centering
\captionsetup{skip=0pt}
\includegraphics[width=6cm]{example-image-a}
\caption{A test caption}
\end{figure}
Output:
Now, instead of just using a graph, I would like to create my own plot in Rmarkdown, for example, using this code:
\begin{figure}
\centering
\captionsetup{skip=0pt}
\includegraphics[width=6cm]{plot(mtcars$mpg)}
\caption{A test caption}
\end{figure}
but the following error is produced instead:
! LaTeX Error: File `plot(mtcars$mpg)' not found.
Is there any way to run r codes within latex?
R Markdown doesn't work this way. If you are using RStudio, it is pretty easy. In the R Markdown file, type
plot(mtcars$mpg)
In other words, you need to start your code with three back-ticks and {r}, and stop your code with three back-ticks again. Your R code written this way will produce the plot you require. After that, click on "knit" button, or use rmarkdown::render(your_file_name).
What you have written in the question means you have produced this chart, and saved that chart as a file in your working directory. If you have saved your plot in the working directory, your code will still work. Try it.
you could try plotting to a file device in an R code chunk e.g.
png(filename="mtcars_mpg.png")
plot(mtcars$mpg)
dev.off()
You can hide this chunk by using include = FALSE in the chunk options.
Then just bring the file in with your LaTeX code:
\begin{figure}
\centering
\captionsetup{skip=0pt}
\includegraphics[width=6cm]{mtcars_mpg.png}
\caption{A test caption}
\end{figure}
Related
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.
I want to apply the fig.pos= 'h' chunk option like so:
```{r echo=FALSE , fig.pos='h'}
ggplot()
```
so that when I knit to pdf latex positions my plots (the float) at the precise location in the LaTeX code. It is my understanding that this should make my latex code look like:
\begin{figure}[h]
\centering
\includegraphics{files/figure-latex/unnamed-chunk-3-1.pdf}
\end{figure}
but instead when I open the generated Tex document I see:
\begin{figure}[htbp]
\centering
\includegraphics{files/figure-latex/unnamed-chunk-3-1.pdf}
\end{figure}
I am ending up with my plots in random postions in the PDF document instead of where they are located in the latex code, sometimes taking up an entire page for one plot. I have tried fig.pos='h', fig.pos='H',fig.pos='h',fig.pos='h!'and fig.pos='H! based on the table on this page.
I am attempting this based on this link where it states under plot chunk options: fig.pos: (''; character) a character string for the figure position arrangement to be used in \begin{figure}[fig.pos]
What am I missing or how else can I ensure my plots are displayed where the text is located within the Rmd file or latex code?
I am using knitr to create a set of lecture slides for a class using R. I would like to create a separate "companion file" that contains just has the R code (corresponding to the slides), so that students can execute the R code by cutting and pasting from the companion file.
For example, in the .Rmd file:
``` {r ....}
plot(x,y)
```
Then there would be a text file with:
plot(x,y)
But, have such a file be automatically produced from the .Rmd file?
Even better if the .Rmd file has such tags:
``` {r basic.plot ....}
plot(x,y)
```
Then, text file has:
# basic.plot
plot(x,y)
Can this be accomplished using knitr?
Yes, this is possible. What you're trying to do is called tangling, and it comes from the world of literate programming.
The knit function supports a tangle option that should be set to TRUE if you want to extract source code.
If a pdf document is created using the following Sweave (R/LaTeX) code, then in the top left of the figure there will be text pdf 2; note this is not embedded in the png but is actually text you can highlight.
In the .Rnw:
\begin{figure}[htb]
\centering
<<fig=FALSE,echo=FALSE>>=
png("test0.png",width=4,height=4,units='in',res=1200)
plot(1)
dev.off()
#
\includegraphics{test0.png}
\caption{Demonstration}
\end{figure}
Then in R:
Sweave("report.Rnw") ; texi2pdf("report.tex")
How do I fix this?
I am using a very recent version of R on Ubuntu.
With the following file
\documentclass{article}
\begin{document}
\begin{figure}[htb]
\centering
<<fig=FALSE,echo=FALSE>>=
png("test0.png",width=4,height=4,units='in',res=1200)
plot(1)
dev.off()
#
\includegraphics{test0.png}
\caption{Demonstration}
\end{figure}
there is a null device 1 message that appears before the plot
It is the output of the R commands that generate the plot.
You can suppress it by adding results=hide.
<<fig=FALSE,echo=FALSE,results=hide>>=
Your message is slightly different because dev.off() returns the name of the current device:
there was none in my case (it was a fresh session),
and a previously opened (but not closed) PDF file in your case.
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: