Multiple plots in a single row - r

From R for Data Science:
To put multiple plots in a single row I set the out.width to 50% for
two plots, 33% for 3 plots, or 25% to 4 plots, and set fig.align =
"default". Depending on what I’m trying to illustrate ( e.g. show data
or show plot variations), I’ll also tweak fig.width, as discussed
below.
How do I put multiple plots on a single row, using the method described above? I could use a package such as patchwork, but the purpose of this post is to understand what's being described above. The R Markdown below doesn't generate what I'd expect, two 'pressure' plots on the same row.
---
title: "Untitled"
author: "April 2018"
date: "4/11/2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Text
```{r pressure1, echo=FALSE, fig.width=6, fig.asp=0.618, out.width="50%", fig.align="default"}
plot(pressure)
plot(pressure)
```
```{r pressure2, echo=FALSE, fig.width=6, fig.asp=0.618, out.width="50%", fig.align="default"}
plot(pressure)
```

I’ve got no idea why your code (or rather, the code from R for Data Science) is not working. But plotting different data makes it work for me:
```{r pressure1, echo=FALSE, fig.width=6, fig.asp=0.618, out.width="50%", fig.align="default"}
plot(cars)
plot(pressure)
```
Alternatively, it seems to be enough to just specify different parameters, e.g.:
plot(pressure)
plot(pressure, main = '')
The fact that inconsequential changes fix the output indicates to me that this is a bug in RMarkdown.
That said, the easiest, most controlled way is to put par(mfrow = c(1, 2)) into the hunk directly before the plotting commands (or a ggplot2 solution such as faceting or {patchwork}).
Tweaking the alignment via the RMarkdown options can be tricky, due to spacing inserted by the conversion to HTML.

You need to specify fig.show = "hold" along with out.width, as you can see here: https://bookdown.org/yihui/rmarkdown-cookbook/figures-side.html

Related

How to reference a plot that is displayed later with bookdown?

This section of the R Markdown Cookbook shows how to create a plot and to display it later in the document:
---
output: bookdown::pdf_document2
---
We generate a plot in this code chunk but do not show it:
```{r cars-plot, dev='png', fig.show='hide'}
plot(cars)
```
After another paragraph, we introduce the plot:
![A nice plot.](`r knitr::fig_chunk('cars-plot', 'png')`)
The problem I have is that I can't reference this plot in the text. See the following code and output:
---
output: bookdown::pdf_document2
---
We generate a plot in this code chunk but do not show it:
```{r cars-plot, dev='png', fig.show='hide'}
plot(cars)
```
Here's a reference to this plot: figure \#ref(fig:cars-plot).
After another paragraph, we introduce the plot:
![A nice plot.](`r knitr::fig_chunk('cars-plot', 'png')`)
Note that if I display the plot immediately, the reference works well:
---
output: bookdown::pdf_document2
---
We generate a plot in this code chunk but do not show it:
```{r cars-plot, fig.cap="A nice plot."}
plot(cars)
```
Here's a reference to this plot: figure \#ref(fig:cars-plot).
How can display the plot later but still be able to reference it? I know that I could simply move the chunk where I want the plot to appear but this is not ideal in my case.
Use ref.label in a later chunk and refer to the later chunk name in the figure reference.
---
output: bookdown::pdf_document2
---
We generate a plot in this code chunk but do not show it:
```{r cars-plot, dev='png', fig.show='hide'}
plot(cars)
```
Here's a reference to this plot: figure \#ref(fig:cars-plot-show).
After another paragraph, we introduce the plot:
```{r cars-plot-show, ref.label="cars-plot", fig.cap="A Nice Plot"}
```

How to create a figure note below the figure caption in r markdown and bookdown

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.

Adding space around figures in RMarkdown

I would like to add space around figures in RMarkdown. I am knitting to PDF and really don't like how close figures (or also equations) are to the text or to the next figure.
---
output: pdf_document
---
```{r pressure, echo=FALSE}
plot(pressure)
```
```{r pressure2, echo=FALSE}
plot(pressure)
```
There is just too little space between the two plots and this gets more fuzzy when using ggplots.
Right now I use the Latex solution
\vspace{10pt}
but it would be nice if I could make a setting globally for the entire document.
Concerning the spacing before and after plots you can use a simple knitr hook:
```{r, echo = F}
library(knitr)
if(is_latex_output()) {
plot_default <- knit_hooks$get("plot")
knit_hooks$set(plot = function(x, options) {
x <- c(plot_default(x, options), "\\vspace{25pt}")
})
}
```
Here we alter the plot hook in that sense that we just add a spacing of 25pt after each plot output.
Concerning equations you can just add these four length definitions at the beginning of your document:
\setlength{\abovedisplayskip}{25pt}
\setlength{\belowdisplayskip}{25pt}
\setlength{\abovedisplayshortskip}{25pt}
\setlength{\belowdisplayshortskip}{25pt}
The first two alter equations created using the align environment. The latter two those created using $$ ... $$.

Changing page size within Rmarkdown document

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

Graphics on next slide with ioslides using Rstudio's Rmd

I want to have my graph output display on the next slide while the code chunk stays on the first. I am using the default ioslides in Rstudio. I would think that it would be some attribute of the code chunk but I can't figure out what it is.
---
output: ioslides_presentation
---
## Slide with Plot
```{r, echo=TRUE}
plot(cars)
```
Any one have any idea on how to do this in Rstudio?
I want to use this for educational purposes. First showing the code and than revealing the graph. Now I am stuck with doing double code chunks with echo=FALSE and TRUE and eval=FALSE and TRUE.
It's easier to run the code twice, once not evaluating the code, the second time not showing the code.
---
title: "Plot Separation"
output: ioslides_presentation
---
## Plot 1
```{r, eval = FALSE}
plot(1:10)
```
## Plot 2
```{r, echo = FALSE}
plot(1:10)
```
It also avoids the error when smaller is true.
To move a plot to the next slide, you need to add a horizontal rule ---- before it (see documentation). You can modify the default plot hook to do it:
```{r setup, include=FALSE}
library(knitr)
local({
hook_plot = knit_hooks$get('plot')
knit_hooks$set(plot = function(x, options) {
paste0('\n\n----\n\n', hook_plot(x, options))
})
})
```
If you want all your plots to appear on the next slide Yihui's answer is the way to go. But if you want some plots to appear on the same slide you may be better off doing it manually, similar to what you are already doing (and what Dario suggested). Except that I would strongly recommend the use of chunk references. That way you avoid the need to duplicate the code.
---
title: "Plot Separation"
output: ioslides_presentation
---
## Plot code
```{r cars_plot, echo = TRUE, eval = FALSE}
plot(cars)
```
## Plot display
```{r cars_plot, echo = FALSE, eval = TRUE}
```
```
I agree this would be desirable, but I'm finding ioslides to be buggy. Ioslides project started eith google, but was let go a while ago.
You may have better luck with beamer/home slides. But does require a LaTeX distribution to be installed.

Resources