在knitr pdf文件中更改单个ggplot2图表的大小

时间:2017-05-24 14:07:47

标签: r ggplot2 knitr

如何在knitr输出pdf中修改ggplot2生成的各个图表的高度和宽度?换句话说,不在代码块选项中使用fig.height和fig.width。我有一些图表在一种尺寸下效果最好,而其他图表则需要不同尺寸。

1 个答案:

答案 0 :(得分:3)

这是一个示例.Rmd文件,用于说明如何执行此操作。最好使用'setup'块来加载和附加命名空间,以及设置选项。每个块都有自己的一组选项,这些选项优先于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}
```

输出pdf的屏幕截图: enter image description here