If I have a chunk that generates 4 figures and I want to keep them all (fig.keep=all), is it possible to show only the second one using a cache option? I see that echo=2:5 can be selected, but it doesn't seem that fig.show=2 is possible. Is the best method to do \includegraphcis{fig2.pdf}?
Thanks.
If you don't want to keep all figures you can simply use :
Use argument fig.keep=c(2,4)
Reproducible example :
\documentclass[a4paper]{article}
\begin{document}
<<load_libraries, echo = FALSE, eval = TRUE, results ="hide">>=
library(knitr)
#
<<multiplefig, fig.keep=c(2,4),fig.height=4,fig.with=10, out.width='.8\\linewidth'>>=
mapply(function(X)plot(X,main=X),c(1:4))
#
\end{document}
However, since you want to keep figures, I would do it the old way in sweave, save the figures using png or pdf.
Reproducible example :
\documentclass[a4paper]{article}
\usepackage{graphicx}
\graphicspath{{figure/}}
\begin{document}
<<multiplefig, echo=FALSE>>=
for (i in 1:4){
png(file=paste0(getwd(),"/figure/fig",i,".png"))
plot(1,1,main=i,cex.main=4)
dev.off()
}
#
This plot shows only figure \ref{fig:fig2} but 4 other are saved
\begin{figure}[htbp]
\centering
\includegraphics[width=0.5\textwidth]{fig2.png}
\caption{}
\label{fig:fig2}
\end{figure}
\end{document}
Related
I am trying to edit an Rtex file and I'm creating plots. I have a plot below, which does compile. However, there is an empty white space below the caption. I can't figure out how to remove it. I have tried to search for solutions but to no avail:
https://support.sisense.com/kb/en/article/remove-whitespace-margins-from-plotly-charts - Relevant but for plotly. Was not
able to adapt it to my R code.
http://ostack.cn/qa/?qa=829717/ - Involved Python rather than R. I
could not adapt the solution into the R plot.
https://tex.stackexchange.com/questions/273786/latex-files-generated-by-tikzdevice-leaves-large-space-between-image-and-caption - Involved tikzpicture instead of R. I could not adapt the solution to the R plot.
The code which I'm running as well as the output is shown below. I am grateful if someone can help me. I have also tried the trimmws() function but it gave the following error:
## "Error in mysub(paste0("^", whitespace, "+"), x): argument"x" is missing, with no default."
\documentclass[a4paper,11pt]{article}
%Packages
\usepackage[justification=centering]{caption}
\usepackage{blindtext}
\begin{document}
\title{F-distribution}
\maketitle
\section{Diagram showing the $F$-distribution for a selected pair of values of the degree of freedom}
\blindtext
\begin{figure}[h!]
<<echo=FALSE, cache=TRUE, fig.width=5, fig.height=5>>=
curve(df(x, df1=20, df2=20))
#
\caption{Hi}
\end{figure}
\blindtext
\blindtext
\end{document}
Your image does have quite a lot of white space around it. You can move the caption further up with this quick hack:
\documentclass[a4paper,11pt]{article}
%Packages
\usepackage[justification=centering]{caption}
\usepackage{blindtext}
\begin{document}
\title{F-distribution}
\maketitle
\section{Diagram showing the $F$-distribution for a selected pair of values of the degree of freedom}
\blindtext
\begin{figure}[h!]
<<echo=FALSE, cache=TRUE, fig.width=5, fig.height=5>>=
curve(df(x, df1=20, df2=20))
#
\vskip-1cm
\caption{Hi}
\end{figure}
\blindtext
\blindtext
\end{document}
Is there an expedient way to extract and load into R a List of Figures that knitr and latex have created in a PDF document?
My PDF has scores of figures; they are sorely in need of being tracked and organized, which the List of Figures helps do. But having the List in R would help in many ways.
Snipping the List from the PDF, pasting it into Excel, and working with that worksheet is one arduous route, but it would be quicker and smoother if it were possible to locate the List of Figures and load it directly (more or less) into R. The knitting process creates many files and perhaps the List lurks within one of them?
Here is a small example simply to create a List of Figures, borrowed from a question on hiding captions here
\documentclass{article}
\usepackage{graphicx}
\setcounter{topnumber}{3}% Just for this example
\begin{document}
\listoffigures
\begin{figure}
\addcontentsline{lof}{figure}{Example image A}%
\centering
\includegraphics[height=4\baselineskip]{example-image-a}
Example image A
\end{figure}
\begin{figure}
\addcontentsline{lof}{figure}{\protect\numberline{}Example image B}%
\centering
\includegraphics[height=4\baselineskip]{example-image-b}
Example image B
\end{figure}
\begin{figure}
\centering
\includegraphics[height=4\baselineskip]{example-image-c}
\caption{Example image C}
\end{figure}
\end{document}
You can do something like this:
---
title: "Untitled"
output:
pdf_document:
fig_caption: true
---
```{r setup, include=FALSE}
gen_lof <- TRUE
if (gen_lof) {
unlink("/tmp/figures.csv")
cat("pdf_name,output_path,caption,subcaption\n",
file="/tmp/figures.csv", append=TRUE)
knitr::knit_hooks$set(plot=function(x, opt) {
cat(x, ",",
opt$fig.path, ",",
opt$fig.cap, ",",
opt$fig.scap, "\n",
sep="", file="/tmp/figures.csv", append=TRUE)
})
}
```
I slightly modified the default RStudio example knitr doc to add two figures with names and captions.
Set gen_lof to FALSE for your normal PDF creation (using a hook mean having to knit once for the full output PDF and once again for just the CSV of figures). Set it to TRUE and knit it to get an list of figures output (wherever you want, I just used that filename for convenience) file that will look like:
pdf_name,output_path,caption,subcaption
Untitled_files/figure-latex/cars-1.pdf,Untitled_files/figure-latex/,lines cars,
Untitled_files/figure-latex/pressure-1.pdf,Untitled_files/figure-latex/,points cars,
While they may have pdf for an output type, it should not be too much trouble to do a 1:1 comparison.
You also have access to all the knitr chunk options this way. i.e.:
aniopts autodep background cache cache.lazy cache.path
cache.rebuild cache.vars child code collapse comment
crop dependson dev dev.args dpi echo engine error eval
external
fig.align fig.cap fig.cur fig.env fig.ext fig.height
fig.keep fig.lp fig.num fig.path fig.pos fig.retina
fig.scap fig.show fig.subcap fig.width
highlight include interval label message out.extra
out.height out.height.px out.width out.width.px
params.src prompt purl ref.label render results
sanitize size split strip.white tidy tidy.opts warning
(I separated out the "fig" specific options on purpose).
The use of a variable to trigger generation means you can code up parameterized knitr workflows to do one gen to get figures and then another to get the final PDF.
Others may have more optimal ways.
As page numbers are not required, it is enough to save fig.cap from each chunk.
This can be done using a chunk hook that saves options$fig.cap in a global variable and saves this variable to a file at the end of the knitting process.
\documentclass{article}
\begin{document}
<<setup>>=
library(knitr)
figureCaptions <- c()
knit_hooks$set(listit = function(before, options, envir) {
if (!before) figureCaptions <<- c(figureCaptions, options$fig.cap)
})
<<fig.cap = "First one", listit = TRUE>>=
plot(1)
#
<<fig.cap = "Second one", listit = TRUE>>=
plot(rnorm(10))
#
<<final>>=
save(figureCaptions, file = "figureCaptions.RData")
#
\end{document}
It should be better to save the caption only after the chunk has been evaluated (if (!before)) in order to avoid problems with eval.after.
To access the captions afterwards, use load("figureCaptions.RData").
I am sorry, I am new to using knitr to make slides. I generally use the latex() function in Hmisc package to generate my tables based on R objects. I would like to produce a slide that shows the r code and then below it displays the properly formatted table. Something like:
``` {r}
latex(tabdat,file="tables/tabdat.tex",ctable=TRUE,caption="A basic table",caption.loc="bottom",label="tab:dat1",row.names=NULL,rowlabel="")
```
So that the finished slide displays the exact r code and the formatted table looking exactly as if I had run latex using \input{tabdat}
I would appreciate any advice on how to accomplish this.
Thanks!
I am a bit puzzled because you talk about PDF/LaTeX output but you are using R markdown tags.
Here are small examples for both cases, R Sweave, i.e. LaTeX output, and R markdown, i.e. HTML output. For creating the LaTeX code there are several packages available (xtable, Hmisc etc.) for HTML AFAIK only xtable.
The main point of how to include the raw output just like it appears in the console is the same for both output types and was already explained by Tyler Rinker above, i.e. by adding results="asis" to the chunk options.
PDF/LaTeX / Rnw-file
\documentclass{article}
\begin{document}
<<echo=FALSE, message=FALSE>>=
library(Hmisc)
library(xtable)
#
<<results='asis'>>=
latex(head(iris), file = '')
#
<<results='asis'>>=
xtable(head(iris))
#
\end{document}
HTML, Rmd-file
```{r echo=FALSE}
library(xtable)
```
```{r results='asis'}
tbl <- xtable(head(iris))
print(tbl, type="html")
```
Look here for more examples and options: http://www.stat.iastate.edu/centers/CCGS/slides/slides-Rtables.pdf
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:
Can't compile the following Rnw document into pdf using knitr
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[russian]{babel}
\begin{document}
<<>>=
hist(rnorm(100),main="Гистограмма")
#
\end{document}
With labels in English everything is ok.
Edit 1:
Now i have two versions of pdf. In the first one letters are replaced by points.
In the second one all letters are overlapped. The second one is produced using addtional code chunk
<<>>=
pdf.options(encoding = "CP1251")
#
I am using Ubuntu 12.04 + R 2.14 + Texlive.
Edit 2:
For the moment i've found the following partial solution:
<<>>=
cairo_pdf("figure.pdf")
hist(rnorm(100),main="Гистограмма")
dev.off()
#
\includegraphics{figure.pdf}
Edit 3:
Using the following code:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[russian]{babel}
\begin{document}
<<dev='cairo_pdf'>>=
hist(rnorm(100),main="Гистограмма")
#
\end{document}
I obtain a CORRECT histogram, with a lot of WARNINGS. How to avoid or at least suppress them?
Finally! Ura!
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[russian]{babel}
\begin{document}
<<dev='cairo_pdf',warning=FALSE>>=
hist(rnorm(100),main="Гистограмма")
#
\end{document}
Could i avoid warnings? Can someone explain me all that stuff with encodings and warnings?
You may need to set pdf.options(encoding = 'your_encoding'); see https://github.com/yihui/knitr/issues/172 I'm not entirely sure what exactly the encoding should be here.