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?
Related
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}
Creating a parameterized report with an rnw file. I am trying to reference specific figures from a code chunk that has multiple figures in it (generated by a loop through a list of figures). I know if there's a single figure I can reference it from the chunk label with \ref{fig:foo} as Yihui mentions in https://bookdown.org/yihui/bookdown/figures.html . But I cannot seem to reference specific figures in the chunk. I tried referencing the unique figure caption or the chunk as a whole but both give me ??. Is there a way to do this?
I searched this Dynamic LaTeX references in R comment with knitr and its linked questions but wasn't able to make it work.
Also in Figures captions and labels in knitr , the plots are combined into one big plot which bypasses the problem.
MVWE:
\documentclass{article}
\usepackage{float}
\usepackage{hyperref}
\usepackage{caption} % Needs to be after hyperref. jumps you to top of figure not to label.
\begin{document}
<<figures, fig.cap=c('fig1','fig2')>>=
library(knitr)
library(markdown)
library(rmarkdown)
library(ggplot2)
figure1 <- ggplot(mtcars) + geom_point(aes(x=mpg,y=cyl))
figure2 <- ggplot(mtcars) + geom_point(aes(x=drat,y=wt))
plots <- list(figure1,figure2)
plots
#
as we can see in \ref{fig:figures}
\end{document}
Just append a number to it:
as we can see in \ref{fig:figures1} and \ref{fig:figures2}
To figure this out, you should look at the .tex file, which contains
\begin{figure}
\includegraphics[width=\maxwidth]{figure/figures-1} \caption[fig1]{fig1}\label{fig:figures1}
\end{figure}
for the first one, and similar stuff for the other. The \label{fig:figures1} part is what your \ref needs to refer to.
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.
I like to generate both pdf and png image files when I create a (latex) document using knitr. This can be done using dev = c("pdf", "png").
However, I don't seem to be able to choose (on a per-figure) basis which of the two is picked in my latex figure environment. Currently the only way in which I can get, say, a png input file for Fig. 1 and a pdf input file for Fig. 2 is to generate only the required format (by using dev = "png", fig.ext = "png").
Is there a way in which I can still generate both, but at the latex level can select which one is shown? It could be solved easily by allowing an extension in the \includegraphics command, I suppose.
Any input appreciated...
Ron
Minimal example:
\documentclass[a4paper,12pt]{article}
%\VignetteEngine{knitr::knitr}
\DeclareGraphicsExtensions{.pdf,.png}
\begin{document}
%\maketitle
<<knitrInitialization,echo=FALSE>>=
require("knitr", quietly=TRUE)
opts_chunk$set(comment=NA,background='transparent',size='small',fig.width=6,fig.height=6,out.width='\\textwidth',dev=c('pdf','png'))
#
%% this one generates two figures, and the pdf version is shown
%% because of the order in DeclareGraphicsExtensions
\begin{figure}[tb]
\centering
<<testPDF,echo=FALSE>>=
plot(1:10)
#
\caption{PDF figure}
\label{fig:pdf}
\end{figure}
%% if I want to show a png (e.g., because the pdf is too large) I can
%% only do that by not generating a pdf in the first place
\begin{figure}[tb]
\centering
<<testPNG,echo=FALSE,dev='png',fig.ext='png'>>=
plot(1:10)
#
\caption{PNG figure}
\label{fig:png}
\end{figure}
\end{document}
You can simply put
\DeclareGraphicsExtensions{.png,.pdf}
in your document when you want PNG to have precedence, and then
\DeclareGraphicsExtensions{.pdf,.png}
later if you want to go back to the PDF preference. This works in the body of a LaTeX document, not just in the header.
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: