Rmarkdown suppress image keeping figure numbering - r-markdown

In writing papers for publication it is often required to keep figures in a separate document (or even a separate document for each figure). In doing so you must manually maintain the figure labels in text i.e. you must write "y was greater than 50% (Figure 1)" in the rmd document rather than something like "y was greater than 50% (Figure #ref(fig:Fig1))". This means that if the figures are rearranged, which is common, then you must manually change all the figure labels to suit the new order.
I am trying to find a way to code in rmd (officedown) that keeps the automatic numbering of the figures within the text but doesn't actually compile the word doc with the figure images.
Below is some example code, I have tried various argument such as fig.show='hide' but without success.
Any and all comments and ideas are welcome in getting to the end result. For example, cross referencing such as in book down in this question. Ideally I would also be able to leave a small amount of text where the actual figure would go as well. Something like 'Figure 1, here' as a simple marker for reviewers but this can be done manually with ease.
---
citation_package: natbib
bibliography: './CompileResources/SBLitRev_Bibli.bib'
biblio-style: 'User/Zotero/styles/ecology-letters.csl'
output:
officedown::rdocx_document:
reference_docx: "./CompileResources/template.docx"
page_size:
width: 8.3
height: 11.7
orient: "portrait"
page_margins:
bottom: 1
top: 1
right: 1.25
left: 1.25
header: 0.5
footer: 0.5
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.cap = TRUE)
library(officedown)
library(officer)
library(rvg)
library(knitr)
fp <- fp_par(
text.align = "center",
padding.bottom = 20, padding.top = 120,
border.bottom = fp_border())```
y was greater than 50% (Figure \#ref(fig:Fig1)).
*Figure 1, here*
```{r fig.cap="Bla bla", include=F, fig.id = "Fig1", fig.cap.style = "Image Caption", fig.show='hide'}
knitr::include_graphics("./Figures/Fig1.pdf")```

Related

Creating two table of contents with different depths in R Markdown

I created my lecture notes in pdf format using RMarkdown but it has many subheaders. Because of this, I want to create two different table of contents: first table of contents with 1 depth, then table of contents in 4 depth respectively.
Adding both toc_depth: 1 and toc_depth: 4 did not work.
My YAML header:
---
title: "Lecture Notes"
author: "x"
output:
pdf_document:
highlight: tango
toc: true
toc_depth: 4 #depth table of contents
number_sections: true
documentclass: article
classoption: a4paper
fontsize: 12pt
geometry: "right=1cm, left=1cm, top=1cm, bottom=3cm"
---
As far as I am aware, I don't believe two Table of Contents is possible. One thing you can try is if you don't want a certain heading numbered, you can do
## Including Plots {-}
Which heads it has a header, but doesn't number it in the TOC. Here is the two output differences
without {-}
with {-}
These can be used in places like the Preface, about the authors, etc.
This is not a perfect solution (maybe some with more knowledge could automate this).
The solution works if the intermediate latex file is kept and a short table of contents is manually added using the shorttoc package.
Adding shortdoc:
...
\documentclass[
]{book}
\usepackage{shorttoc}
...
And than adding it between title and TOC:
\shorttableofcontents{〈title 〉}{〈depth 〉}

Rmarkdown officer / officedown / flextables problem

I have the following rmd script. I've spent a few days trying to get this to work but I am failing miserably. Basically I need help with three things. I am happy to post three separate questions if needed.
The multicolumn options/code are completely ignored. The corporatetable.docx is in landscape and has a typical corporate style. I need to have a full width landscape -> two column landscape -> full width landscape. If I could get the two column landscape setup to work, the remaining style would be inherited by corporatetable.docx. If I could get help with only one - I would need this.
When I run the rmd it generates a word file but none of the corporate styles are in there. It just uses my word's default colors etc. The difference is very clear - no landscape, single column and blue instead of red. How do I correctly pass the officedown::rdocx_document: to reference my word file because it's clearly not picking it up and no warning or error is generated?
If you see in the second chunk I am using flextable to show two pictures (which are passed through params) in the word report and align them with some information. myft works but it prints the (temporary/volatile) path instead of showing the pictures in the report. For reference if I use knitr::include_graphics(c(params$x1,params$x2)) it works fine.
I'm really stuck on these. Any help is welcome.
---
title: "Title"
subtitle:
params:
x1: x1
x1_name: x1_name
x1_email : x1_email
x2: x2
x2_name: x2_name
x2_email : x2_name
output:
officedown::rdocx_document:
reference_docx: corporatetemplate.docx
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(officedown)
library(officer)
library(flextable)
knitr::opts_chunk$set(out.width = '100%', dpi=300)
```
<!---BLOCK_MULTICOL_START--->
This text is on column 1. Please work
```{r somecodechunk, echo=FALSE, out.width="75px", include=TRUE, strip.white=TRUE}
library(flextable)
# this works but prefer to use flextable
# if(all(!is.null(params))) {
# knitr::include_graphics(c(params$x1,params$x2))} else {
# }
myft <- data.frame(
"pic1" = rep("",3),
"details1" = c(params$x1_name,"+X XXX XXX X",params$x1_email),
"pic2" = rep("",3),
"details2" = c(params$x2_name,"+X XXX XXX X",params$x2_email)
)
myft <- flextable(myft)
myft <- merge_at(myft, i = 1:3, j = 1 )
myft <- merge_at(myft, i = 1:3, j = 3 )
myft <- compose(myft,i = 1, j = 1, value = as_paragraph(as_image(params$x1), part = "body"))
myft <- compose(myft,i = 1, j = 3, value = as_paragraph(as_image(params$x2), part = "body"))
autofit(myft)
#Ok this does not work because the pics are not shown
```
`r run_columnbreak()`
This text is on column 2. Please work
This text is on column 2. Please work
`r run_linebreak()`
<!---BLOCK_MULTICOL_STOP{widths: [4,4], space: 0.2, sep: true}--->
\pagebreak
Back to full width with some text
\pagebreak

Change Default Beamer slide size

In R markdown when using Beamer slides if you try to plot you need to specify the plot sizes (unlike in the reports) so that the plots fit on a page. This can often result in the plots appearing to be squashed together, as apposed to just a smaller version of the plot.
Is there some method to change the default slide size to alleviate this problem?
I have tried
header-includes:
- \usepackage[papersize={25.6cm,19.2cm}]{geometry}
in the yaml header, and I get the error
! LaTeX Error: Missing \begin{document}.
Using R Markdown I shouldn't need to use this though.
A reproducible example is shown below
---
title: "Plots look bad"
author: "Beavis"
date: "`r format(Sys.time(), '%d/%m/%Y')`"
output: beamer_presentation
header-includes:
- \usepackage{float}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
knitr::opts_chunk$set(results = 'hide')
knitr::opts_chunk$set(warning = FALSE)
knitr::opts_chunk$set(cache=TRUE)
knitr::opts_chunk$set(fig.height=3.5)
```
# Introduction
```{r}
pca <- prcomp(iris[,1:4])
biplot(pca)
```
Here, you if you run this the second slide looks like this As you can see the plot is rubbish. What is the best way to avoid this problem?
The biplot function uses par(pty = "s") to force a square plot, so it's not going to fill a rectangular slide. You can make it look better by asking the fig.height to be bigger, but then it will overflow the bottom of the slide. To prevent this, you can set both fig.height to a large number, and out.height (which will be a LaTeX measurement) to something that will fit on a slide. For example, using this chunk
```{r fig.height=10, out.height="0.8\\textheight"}
pca <- prcomp(iris[,1:4])
biplot(pca)
```
I see this output:
I'd recommend a smaller fig.height, but your preference may be different.
Both fig.height and out.height could be specified using knitr::opts_chunk$set as defaults for all slides if you want.
You could also specify out.width="\\textwidth" for a really ugly stretched plot that fills the slide, but I wouldn't recommend it.

Plot annotation in R-Markdown + tikzDevice

I'm preparing a presentation using R-Markdown + Beamer, and want every plot annotation to be typeset with a serif font.
Here's a minimal example (in order to run this, the code should be pasted in a .Rmd file and compiled with knitr):
---
title: An example
subtitle: which should work
output:
beamer_presentation:
theme: metropolis
header-includes:
\usefonttheme[onlymath]{serif}
---
## A slide
```{r test, echo=FALSE, fig.height=3.2, fig.width=4, fig.align='center', dev='tikz', external=FALSE}
plot(2*pi*(0:19)/20, sin( 2*pi*(0:19)/20 ), xlab = '$x$', ylab='$\\sin(2\\pi x)$', pch=21, bg=rgb(0,.4,.7,.5), main='A plot using \\LaTeX', font.main=1)
```
In the generated plot, I expect the font annotations in the axes' numbering, plot title, etc, to be typeset with a serif font (the same fonts that appear in math annotations), but the actual output is typesetting with a sans-serif font. It is important that the rest of the document still typesets with sans-serif fonts.
That is because the plots are compiled in seperate tex files. To change anything about the plots you should change the tikzLatexPackages option. The default is
options(
tikzLatexPackages = c(
"\\usepackage{tikz}",
"\\usepackage[active,tightpage]{preview}",
"\\PreviewEnvironment{pgfpicture}",
"\\setlength\\PreviewBorder{0pt}")
),
tikzXelatexPackages = c(
"\\usepackage{tikz}\n",
"\\usepackage[active,tightpage,xetex]{preview}\n",
"\\usepackage{fontspec,xunicode}\n",
"\\PreviewEnvironment{pgfpicture}\n",
"\\setlength\\PreviewBorder{0pt}\n"
),
tikzLualatexPackages = c(
"\\usepackage{tikz}\n",
"\\usepackage[active,tightpage,psfixbb]{preview}\n",
"\\usepackage{fontspec,xunicode}\n",
"\\PreviewEnvironment{pgfpicture}\n",
"\\setlength\\PreviewBorder{0pt}\n")
)
So adding \usefonttheme[onlymath]{serif} to that first option should do it.
You can find more info on this on page 6 of the tikzDevice manual.
Note that it is also possible to include the tex code rather then the precompiled code. Though I had some issues with this approach in the past.

Is there a way to have previous/next links at the bottom of shiny presentations?

I am working in RStudio and creating a markdown Shiny presentation (which I believe uses IOslides).
Currently the generated presentation doesn't have any navigational help, the user has to know they need to use left/right arrows to move to the next or previous slides. Even when deployed to server I don't see any arrows at the bottom of presentations.
I have searched through documentation and here to see if this is possible, but can't seem to find anything.
Is there some setting to include a Previous/Next type link at the bottom of every slide?
Process to create my presentation in R Studio:
New file > R Markdown > Shiny > Shiny presentation
The issue occurs even with the sample code when creating a new file - there are no navigation arrows
Published example (where there are no navigation arrows):
https://regolith.shinyapps.io/test
And the sample code (as generated by R studio):
---
title: "test"
author: ""
date: "24 January 2017"
output: ioslides_presentation
runtime: shiny
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## Shiny Presentation
This R Markdown presentation is made interactive using Shiny. The viewers of the presentation can change the assumptions underlying what's presented and see the results immediately.
To learn more, see [Interactive Documents](http://rmarkdown.rstudio.com/authoring_shiny.html).
## Interactive Plot
```{r eruptions}
inputPanel(
selectInput("n_breaks", label = "Number of bins:",
choices = c(10, 20, 35, 50), selected = 20),
sliderInput("bw_adjust", label = "Bandwidth adjustment:",
min = 0.2, max = 2, value = 1, step = 0.2)
)
renderPlot({
hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks),
xlab = "Duration (minutes)", main = "Geyser eruption duration")
dens <- density(faithful$eruptions, adjust = input$bw_adjust)
lines(dens, col = "blue")
})
```
## Bullets
- Bullet 1
- Bullet 2
- Bullet 3
## R Output
```{r cars}
summary(cars)
```