简体   繁体   中英

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.

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: 在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM