I have a very large phylogenetic tree that I'd quite like to insert into a supplementary material I'm writing using Rmarkdown and knitr. I dislike splitting trees across pages and I doubt anybody would print this out anyway so I thought I'd just have a large page in the middle of the pdf I'm generating.
The question is how do I change page size for one page in an otherwise A4 document? I'm pretty new to knitr and I've found global paper size options but I'm struggling to find ways of setting up what would be the equivalent of sections in Word.
(Update) Hi does anybody else have a suggestion? I tried the pdfpages package but this seems to result in an equally small figure on a page the size of the pdf that is being pasted in i.e. if I make a 20in by 20in pdf figure then paste the page in using \includepdf then I get a 20in by 20in page with a much smaller figure on it (the same as the \eject example above). It seems like knitr or Latex is forcing the graphics to have a specific size regardless of page size. Any ideas? Here's a reproducible example:
---
title: "Test"
output:
pdf_document:
latex_engine: xelatex
header-includes:
- \usepackage{pdfpages}
---
```{r setup, include=FALSE}
require(knitr)
knitr::opts_chunk$set(echo = FALSE,
warning=FALSE,
message=FALSE,
dev = 'pdf',
fig.align='center')
```
```{r mtcars, echo=FALSE}
library(ggplot2)
pdf("myplot.pdf", width=20, height=20)
ggplot(mtcars, aes(mpg, wt)) + geom_point()
dev.off()
```
#Here's some text on a normal page, the following page is bigger but has a tiny figure.
\newpage
\includepdf[fitpaper=true]{myplot.pdf}
You should be able to use \ejectpage like this:
---
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
\eject \pdfpagewidth=20in \pdfpageheight=20in
```{r mtcars}
library(ggplot2)
ggplot(mtcars, aes(mpg, wt)) + geom_point()
```
\eject \pdfpagewidth=210mm \pdfpageheight=297mm
Back
(I can only remember the A4 height in mm for some reason)
I have just faced the same struggle when dealing with a large phylogenetic tree.
Based on hrbrmstr's answer, I came up with the snippet below.
The trick is to make knitr generate the figure but not include it in the intermediate .tex right away (hence fig.show="hide"). Then, because figure paths are predictable, you can insert it with some latex after the code chunk.
However, the new page height is not taken into account when positioning page numbers, so they tend to be printed over your image. I have tried to overcome this behavior multiple times, but in the end I simply turned them off with \thispagestyle{empty}.
---
output: pdf_document
---
```{r fig_name, fig.show="hide", fig.height=30, fig.width=7}
plot(1)
```
\clearpage
\thispagestyle{empty}
\pdfpageheight=33in
\begin{figure}[p]
\caption{This is your caption.}\label{fig:fig_name}
{\centering \includegraphics[height=30in, keepaspectratio]{main_files/figure-latex/fig_name-1} }
\end{figure}
\clearpage
\pdfpageheight=11in
Related
I am struggling to create a figure note below the figure caption in r markdown and bookdown. The figure note I want looks like below. This figure is from (Greenstone and Hanna 2014). My figure actually is a
r plot. The note should be the same length as the figure width and automatically break the line. Any ideas???
If you are using a format that goes through LaTeX (e.g. pdf_book or pdf_document), this is possible. I don't know if there's a way to do it with HTML output. (But does that move figures around? Maybe plain text below the figure is enough). The idea is to enter the LaTeX code to
start and end the figure yourself, and include the note within that block. Here's an example, based on the standard pdf_document example.
---
title: "Untitled"
output:
pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Including Plots
You can also embed plots, for example: Figure \ref{fig:pressure}.
```{=latex}
\begin{figure}[t]
```
```{r pressure, echo=FALSE}
plot(pressure)
```
```{=latex}
\caption{Air quality monitors across India. \label{fig:pressure}}
\textit{Notes:} Dots denote cities with monitoring stations
under India's National Ambient Air Monitoring Programme
(NAAMP). Geographical data are drawn from MIT's Geodata
Repository.
\end{figure}
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Does anybody know why R markdown generates excessive white space above each plot and how can I fix that ? Is there a knitr option to be included ? Or any chunk option maybe ?
I've provided 3 images at the bottom of this post so that you can see what I mean.
Haven't used any other chunk option than echo, warning and message and about the plot it is a basic ggplot.
Let me know in the comments if I need to provide any code example of my chunks for a better view.
Edit: here's a simple rmarkdown file generating the same excessive white space above ggplots.
---
title: "Untitled"
author: "Razvan Cretu"
date: "January 9, 2019"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r import, echo=FALSE}
library('ggplot2')
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
ggplot(cars, aes(speed, dist))+
geom_line()
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
I would like to edit a single rmarkdown (Rmd) document with a list of "problems", each followed by its solution. Each solution may contain the results of the R console, but also some explaining (markdown and LaTeX formatted) text. Besides, I would like use knitr in 2 versions: with and without the solutions, changing the source as less as possible, and compiling.
I know that I can use a logical variable in order to conditionally evaluate R code and show plots and R output, but I don't know how to show/hide blocks of (markdown and LaTeX) formatted text, unless I put all that text into R character vectors, which seems hard for keeping things clean and readable.
I found this old question,
Conditionally display a block of text in R Markdown
where the solution was given for simple short text, which was included as an argument of the R print() function.
This other old question,
insert portions of a markdown document inside another markdown document using knitr
was for having a father document and child documents which were conditionally compiled, but I don't want to slice my document into so many pieces.
You could use the asis engine to conditionally include/exclude arbitrary text in knitr, e.g.
```{asis, echo=FALSE}
Some arbitrary text.
1. item
2. item
Change echo=TRUE or FALSE to display/hide this chunk.
```
But I just discovered a bug in this engine and fixed it. Unless you use knitr >= 1.11.6, you can create a simple asis engine by yourself, e.g.
```{r setup, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
if (options$echo && options$eval) paste(options$code, collapse = '\n')
})
```
If you want to include inline R expressions in the text, you will have to knit the text, e.g.
```{r setup, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
if (options$echo && options$eval) knit_child(text = options$code)
})
```
There is a way to hide parts of the document (including text and chunks): to comment them out with html comment marks.
And comment marks can be generated by R in a block according to a variable that can be set at the beginning of the document.
```{r results='asis', echo=FALSE}
if (hide) {cat("<!---")}
```
```{r results='asis', echo=FALSE}
if (hide) {cat("-->")}
```
And just to show a complete working example, in the example below the middle section of the document can be shown or hidden by setting the hide variable to FALSE or TRUE. That might be useful in case there are several sections to hide or show at once - for example, solutions of course problems.
---
title: "Untitled"
date: "15/10/2020"
output:
word_document: default
html_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
hide <- TRUE #TRUE to comment out part of the document, FALSE to show.
```
## Start
Always shown.
```{r}
hide
```
```{r results='asis', echo=FALSE}
if (hide) {cat("<!---")}
```
## To hide or not to hide
To be hidden or shown according to *hide* variable.
```{r}
"Also to be hidden according to 'hide' variable"
hist(rnorm(10))
```
```{r results='asis', echo=FALSE}
if (hide) {cat("-->")}
```
<!--
Never shown.
-->
## End
Always shown.
Just a caveat: in html output the hidden parts are kept as comments and can be seen just by viewing the source. On the other hand, PDF (LaTex) and Word outputs ignore html comments and the hidden parts aren't included in the knitted documents.
Therefore, when the hidden parts are supposed to be somehow confidential (e.g. exam solutions) PDF or Word output should be used instead of html.
For those looking for a solution when knitting to pdf through LaTex, the answer from #Pere won't work for you (because LaTex doesn't understand the <!--- --> pair as indicating a comment).
Below is one possible workaround:
---
output:
pdf_document
---
\newcommand{\ignore}[1]{}
```{r echo=FALSE}
include <- TRUE
```
```{r results='asis', echo=FALSE}
if(!include){cat("\\ignore{")}
```
Included bla bla
```{r results='asis', echo=FALSE}
if(!include){cat("}")}
```
```{r echo=FALSE}
include <- FALSE
```
```{r results='asis', echo=FALSE}
if(!include){cat("\\ignore{")}
```
NOT Included bla bla
```{r results='asis', echo=FALSE}
if(!include){cat("}")}
```
Jallen produced a solution for producing knitr plots, labels, and captions within one chunk - for Rnw files.
knitr plots, labels, and captions within one chunk
This works nicely for .Rnw but I can't make it work for .Rmd, don't see what is going wrong...
---
output:
pdf_document:
fig_caption: yes
fig_crop: no
---
```{r startup,echo=FALSE,results='hide',message=FALSE,tidy=FALSE,warning=FALSE,fig.keep='all',comment=NA}
require(knitr)
require(ggplot2)
opts_knit$set(progress = F, verbose = F)
opts_chunk$set(comment=NA,
tidy=FALSE,
warning=FALSE,
message=FALSE,
echo=FALSE,
dpi=600,
fig.width=6.75, fig.height=4, # Default figure widths
dev=c("pdf",'tiff'),
dev.args=list(pdf=list(NULL),tiff=list(compression='lzw')),
error=FALSE)
```
```{r plotloop,results='asis'}
for(x in seq(1,20)){
x1<-data.frame(x=seq(1,10),y=seq(1,10))
plt<-ggplot(data=x1,aes(x,y))+geom_point()
figLabel=paste('Figure',x,sep='')
capt<-paste('Caption for fig.',x)
cat(knit(text=(paste("```{r ",figLabel,",fig.pos='h',fig.cap='",capt,"'}\nplt\n```",sep=''))))
cat('\\newpage')
plot.knit function in knitr plots, labels, and captions within one chunk can be modified to account for the syntax of markdown as opposed to latex. plot.knit.md becomes
plot.knit.md<-function(chunkLabel,#text for chunk label which is also used for figure file name
capt,#text for caption
plt,
...)
{
cat(knit(text=knit_expand(text="```{r, {{chunkLabel}},eval=TRUE,fig.cap='{{capt}}',echo=FALSE}\nplt\n```"),
quiet=TRUE))
}
This works in the following markdown doc.
---
title: "plot.knit.md demo"
author: "Joel Allen"
date: "04/23/2015"
output:
html_document: default
pdf_document:
fig_caption: yes
---
This is an R Markdown document to demonstrate the generation of self-contained code chunks in a markdown file. It is particularly useful for situations where multiple plots are generated in a single code chunk allowing for dynamic label and caption support.
This example draws on
http://stackoverflow.com/questions/21685885/knitr-plots-labels-and-captions-within-one-chunk
in response to
https://stackoverflow.com/questions/27443019/knitr-plots-labels-and-captions-within-one-chunk-rmd-files
Items to note:
#. output pdf_document fig_caption option must be set to yes
#. plot.knit has been modified to plot.knit.md to account for the different syntax needed.
```{r, echo=FALSE,results='asis'}
plot.knit.md<-function(chunkLabel,#text for chunk label which is also used for figure file name
capt,#text for caption
plt,
...)
{
cat(knit(text=knit_expand(text="```{r, {{chunkLabel}},eval=TRUE,fig.cap='{{capt}}',echo=FALSE}\nplt\n```"),
quiet=TRUE))
}
require(ggplot2)
cars.p<-ggplot(cars,aes(x=speed,y=dist))+
geom_point()
plot.knit.md(chunkLabel="carsPlot",capt="this is a caption for the cars plot",plt=cars.p)
```
One thing to figure out though is the attachment of labels...
I am using knitr and pandoc to write reports into word (we need to be able to circulate for comments using track changes etc).
It is working very well so far, but I have found that the plots are all coming out with captions at the bottom, and I don't want captions. While I could just delete them in the word doc, if I can stop them showing in the code it would be better.
So for the following code in markdown:
Test test test
```{r}
summary(cars)
```
You can also embed plots, for example:
```{r fig.width=7, fig.height=6}
plot(cars)
```
I then run the following code in R:
library("knitr")
# Stackoverflow table test 1.html
knit2html("captiontest.rmd")
FILE <- "captiontest"
system(paste0("pandoc -o ", FILE, ".docx ", FILE, ".md"))
And the graph, in the word document, has the caption "plot of chunk unnamed-chunk-2"
I know I can change this caption, e.g. {r fig.width=7, fig.height=6, fig.cap='hello'}, but I thought that fig.cap=NULL would make it hidden. Instead it seems to make the whole plot disappear.
Are plots required to have a caption - do I just have to go through each word doc and delete them manually? Or is there a way to hide them?
Kind of a dirty trick, but:
You can set fig.cap="" on the chunk in question:
Test test test
```{r}
summary(cars)
```
You can also embed plots, for example:
```{r fig.width=7, fig.height=6, fig.cap=""}
plot(cars)
```
Or, you can set fig.cap="" for all chunks at once in an initializing chunk at the beginning of your Rmd document:
Test test test
```{r options-chunk}
opts_chunk$set(fig.cap="")
```
```{r}
summary(cars)
```
You can also embed plots, for example:
```{r fig.width=7, fig.height=6}
plot(cars)
```