更改Knitr pdf文件中单个ggplot2图表的大小 [英] Change size of individual ggplot2 charts in knitr pdf file

查看:168
本文介绍了更改Knitr pdf文件中单个ggplot2图表的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

下面是一个示例.Rmd文件,以演示如何执行此操作.最好使用设置"块来加载和附加名称空间,并设置选项.每个块可以有自己的一组选项,这些选项将优先于opts_chunk$set()设置的选项.

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}
```

输出pdf的屏幕截图:

A screenshot of the output pdf:

这篇关于更改Knitr pdf文件中单个ggplot2图表的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆