Neal
Neal

Reputation: 199

Change size of individual ggplot2 charts in knitr pdf file

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.

Upvotes: 3

Views: 3225

Answers (1)

Peter
Peter

Reputation: 7790

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: enter image description here

Upvotes: 4

Related Questions