ggplot 绘图中的字体大小与使用 knitr 的绘图有关

Size of font in ggplot plot changes in relation to plot using knitr

我是第一次使用 knitr,在 ggplot 绘图中遇到字体大小问题。这是一个示例图:

d <- ggplot(diamonds, aes(x = cut, y = clarity))
d + stat_sum(aes(label=..n..),geom="text",size=8)

在 knitr 中,我在 R markdown 中的块中有相同的情节:

---
title: "Untitled"
output: html_document
---
```{r, echo=FALSE}
library(ggplot2)
d <- ggplot(diamonds, aes(x = cut, y = clarity))
d + stat_sum(aes(label=..n..),geom="text",size=8)
```

该图在 RStudio 中或使用 ggsave() 保存时看起来不错。然而,生成的 knitr html 中绘图中的数字总体上和相对于绘图大小的字体大小要大得多:

在这个例子中,这无关紧要,但在我的数据中,数字开始相互重叠/运行 在它们的单元格之外。

更复杂的是情节是由一个包完成的,所以我不能轻易地在 stat_sum 调用中更改大小选项。

尝试调整 fig.heightfig.width:

---
title: "Untitled"
output: html_document
---
```{r, echo=FALSE,fig.height=10,fig.width=10}
library(ggplot2)
d <- ggplot(diamonds, aes(x = cut, y = clarity))
d + stat_sum(aes(label=..n..),geom="text",size=8)
```

如果不想图太大,可以调整out.heightout.width:

---
title: "Untitled"
output: html_document
---
```{r, echo=FALSE,fig.height=10,fig.width=10,out.height=600,out.width=600}
library(ggplot2)
d <- ggplot(diamonds, aes(x = cut, y = clarity))
d + stat_sum(aes(label=..n..),geom="text",size=8)
```