Change size of individual ggplot2 charts in knitr pdf file

亡梦爱人 提交于 2019-12-11 03:05:38

问题


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.


回答1:


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:



来源:https://stackoverflow.com/questions/44160821/change-size-of-individual-ggplot2-charts-in-knitr-pdf-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!