【问题标题】:Change size of individual ggplot2 charts in knitr pdf file更改 knitr pdf 文件中单个 ggplot2 图表的大小
【发布时间】:2017-05-24 14:07:47
【问题描述】:

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

【问题讨论】:

  • 你能不能把这些数字分成不同的块?
  • 根本不使用 fig.height/fig.width?因为你可以在代码块中添加多个值:fig.height = c(3,2), fig.width = c(5,4)
  • @Richard Telford 我不知道我可以在不同的块中使用不同的选项。我一直只是在第一个块中设置选项...
  • 我会把它放在一个叫做 setup 的块中,没有别的东西(除了 library())。其他一切的新块
  • fig.height = c(3,2), fig.width = c(5,4) 在块选项中将使第一个数字 3 * 5 英寸和第二个 2 * 4 (不知道你可以这样做)。

标签: r ggplot2 knitr


【解决方案1】:

这里有一个示例 .Rmd 文件来展示如何执行此操作。最好使用“设置”块来加载和附加命名空间,并设置选项。每个块都可以有自己的一组选项,这些选项将优先于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的截图:

【讨论】:

    猜你喜欢
    • 2017-12-14
    • 2020-12-15
    • 1970-01-01
    • 2013-05-22
    • 2021-11-24
    • 2016-03-13
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多