Change size of individual ggplot2 charts in knitr pdf file - r

How can I modify the height and width of individual charts produced by ggplot2 in a knitr output pdf? In other words, not using the fig.height and fig.width in the code chunk options. I have some charts that work best at one size and others that need to be a different size.

Here is an example .Rmd file to show how to do this. It would be preferable to use a 'setup' chunk to loaded and attached namespaces, and to set options. Each chunk can have its own set of options which will take precedence over the options set by opts_chunk$set().
---
title: Change size of individual ggplot2 charts in knitr pdf file
output: pdf_document
---
It would be preferable to set chunk options only once, in a "setup" chunk.
Then, as needed, modify the options for each following chunk as needed. The
chunk options `include = FALSE, cache = FALSE` are helpful for the set up chunk
so that it will be evaluated every time the file is knitted, but will not create
any lines within the intermediate or final file.
```{r setup, include = FALSE, cache = FALSE}
library(ggplot2)
library(knitr)
opts_chunk$set(fig.width = 12, fig.height = 8)
```
The first figure will have the default size of 12 by 8 inches, although it is
scaled to to fit the pdf page.
```{r figure1}
ggplot(mpg) + aes(x = manufacturer, y = cty) + geom_boxplot() + coord_flip()
```
This figure can be made again, but with a different size.
```{r figure2, ref.label = "figure1", fig.width = 4, fig.height = 3}
```
A screenshot of the output pdf:

Related

How to reduce (white) margin of a waffle chart?

I' d like to ask some help on how to reduce the amount of white space in a waffle chart using the waffle package in R.
Here's the code:
waffle(table(dat$Age.Group),
rows=5,
title="Demographic Age Groups")
Then it shows this:
When I knitt it, it takes too much space, refer to the picture:
I'd like to put the text closer to the plot so it won't look awkward, and so I can fit more waffle charts in one page.
I really haven't tried anything, except changing the spacing between the squares, but that doesn't seem to be the problem. I've also looked up similar problems, but I can't find anything addressing to the removing of the margin.
Thank you so much in advance!
The issue is that waffle uses coord_equal under the hood. As a result the size of the plot is not adjusted to fill the size of the output device. If the size of the output device is larger than needed for the plot it is filled up with white space.
One option would be to set equal=FALSE in waffle. However, in that case you will no longer get squares but rectangles.
Second option would be to reduce the size or the height of the output device via chunk options, i.e. the size used by Rmarkdown or knitr to render your plot which by default is a 7 x 7 inches. To this end you could set fig.height or as an alternative set the aspect ratio using fig.asp:
---
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r, include=FALSE}
library(waffle)
```
```{r, include=FALSE}
parts <- c(One=80, Two=30, Three=20, Four=10)
chart <- waffle(parts, rows=8, equal = FALSE)
```
```{r fig.cap="Default"}
chart + ggplot2::labs(title = "Default")
```
```{r fig.asp=.4, fig.width = 7, fig.cap="Set the aspect ratio"}
chart + ggplot2::labs(title = "Set the aspect ratio")
```
```{r fig.height = 2.8, fig.width = 7, fig.cap="Reduce the figure height"}
chart + ggplot2::labs(title = "Reduce the figure height")
```

How do I get Bookdown to properly knit a PDF with multiple code chunks?

I am transitioning to Bookdown from Markdown. Although it seems as though this should be straightforward I am getting an unexpected knit failure once I have added the 3rd (usually) code chunk in a chapter (not index.rmd) file. I have tried using code from the example code by Allaire and Xie with the same result. The problem does not occur if all the markdown code is in one file i.e. no chapters. Here is the sample code from the index and 1st chapter files. Sorry about the formatting; I'm not sure how to format markdown code in stackoverflow so the 3 back tics consistently show.
---
classoption: openany # Removes blank pages (Arrgh!!)
site: "bookdown::bookdown_site"
output:
bookdown::tufte_book2:
latex_engine: xelatex
---
```{r setup, include=FALSE}
library(ggplot2)
# invalidate cache when the tufte version changes
knitr::opts_chunk$set(tidy = FALSE, cache.extra = packageVersion("tufte"))
```
And this is the first chapter code:
# Figures
## Margin Figures
Images and graphics play an integral role in Tufte's work. To place figures in the margin you can use the **knitr** chunk option `fig.margin = TRUE`. For example:
```{r fig-margin, fig.margin = TRUE, fig.cap = "MPG vs horsepower, colored by transmission.", fig.width=3.5, fig.height=3.5, cache=TRUE, message=FALSE}
library(ggplot2)
mtcars2 <- mtcars
mtcars2$am <- factor(
mtcars$am, labels = c('automatic', 'manual')
)
ggplot(mtcars2, aes(hp, mpg, color = am)) +
geom_point() + geom_smooth() +
theme(legend.position = 'bottom')
```
In fact, you can include anything in the margin using the **knitr** engine named `marginfigure`. Unlike R code chunks ```` ```{r} ````, you write a chunk starting with ```` ```{marginfigure} ```` instead, then put the content in the chunk. See an example on the right about the first fundamental theorem of calculus.
```{marginfigure}
We know from _the first fundamental theorem of calculus_ that for $x$ in $[a, b]$:
$$\frac{d}{dx}\left( \int_{a}^{x} f(u)\,du\right)=f(x).$$
```
It fails here
knitr::kable(
mtcars[1:6, 1:6], caption = 'A subset of mtcars.'
)
Deleting the code after "It fails here" makes it knit properly for me.
Dropbox link with scripts, log, and pdf's.

Inline plot size and knitted plot size don't agree in RStudio on retina display

It turns out that setting plot sizes on a Mac with retina display can be challenging. I am not referring to file sizes or resolutions that can be taken care of with the fig.retina setting (I have seen several questions about that), but the fact that the actual figure layout differs between the inline version of a an RMarkdown script and both an exported version with the same dimensions (using ggsave) as well as a knitted version. Even small figure dimensions appear gigantic inline on the screen while they export and knit correctly. So, the ratio between font size and "plot size" (or whatever it would be called) appears to change. If I run the code on an older (non-retina) Macbook or a PC, the inline figure sizes are as expected.
This is an example of what I mean. The specified figure dimensions were fig.width=4, fig.height=3.
Is there a way to get the inline graph dimensions match the knitted versions...?
Thanks y'all!
edit: code included, not sure how reproducible it is though, since it might only be relevant to users with retina or 4k displays:
---
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
```
```{r, fig.width=4, fig.height=3}
Pdata <- data.frame("X" = 1:10, "Y" = 1:10) # some data
ggplot(data = Pdata,aes(x = X,y = Y)) +
geom_point() +
theme_bw(base_size = 20) +
labs(x = "Some stuff", y = "Some more stuff")
```

Figure captions with multiple plots in one chunk

I label my figures like this.
---
title: "xxx"
output:
pdf_document:
fig_caption: true
---
And then in each chunk
```{r, fig.cap="some caption"}
qplot(1:5)
```
This works quite nicely. However in chunks where I plot multiple figures within a loop I can't specify a caption. This produces no caption at all:
```{r, fig.cap="another caption"}
qplot(1:5)
qplot(6:10)
```
How can I specify a figure that counts from the same number as the first chunk for each plot?
You can use a fig.cap argument of length 2 (or the size of your loop):
```{r, fig.cap=c("another caption", "and yet an other")}
qplot(1:5)
qplot(6:10)
```
Found an easy way to dynamically produce plots and add them to the pdf with individual captions, using knitr::fig_chunk as described here. This is also a workaround for OPs comment that message=false (or echo=False or results='asis' for that matter) supresses the fig.cap argument.
```{r my-plots, dev='png', fig.show='hide', echo=FALSE}
# generate plots first
qplot(1:5)
qplot(6:10)
```
```{r, echo=FALSE, results='asis'}
# then put them in the document with the captions
cat(paste0("![some caption](", fig_chunk(label = "my-plots", ext = "png", number = 1), ")\n\n"))
cat(paste0("![another caption](", fig_chunk(label = "my-plots", ext = "png", number = 2), ")\n\n"))
```
Hopefully this helps someone who stumbles upon this question in the future.

Specify height and width of ggplot graph in Rmarkdown knitr output

I have created a plot with ggplot2 where the x-axis labels are not readable unless the plot is larger than default. When viewing in Rstudio I am able to resize dynamically. When saving with ggsave() I am able to specify height and width. How would I do this within the Rmarkdown file so that the output contains a plot of the desired size?
You can specify height and width in the code chunks
```{r, fig.width=10,fig.height=11}
df %>% ggplot(aes(x = x, y = y)) + geom_point()
```
As a side-answer, note that you can also use metric-system units using ggplot2::unit():
library(ggplot2)
knitr::opts_chunk$set(fig.width=unit(18,"cm"), fig.height=unit(11,"cm"))
If you would like to do this for all plots then you can use the r setup Rmd chunk at the beginning of the file.
knitr::opts_chunk$set(echo = TRUE, fig.width = 10, fig.height = 5)

Resources