使用较高的字体大小时,ggplot2分面标签的边距太大

5

当在rmarkdown中增加字体大小以补偿高dpi渲染时,facet wrap ggplot图像的标签具有异常大的边缘。在下面的示例中,上方 'D'、'E'等字母上方的垂直空间是我想要降低的。我已尝试更改element_text边距以及panel.spacing主题参数。将它们设置为零并没有太大的改变。

代码

---
title: "PNG facet wrap test"
output:
  word_document: default
  html_document: default
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, warning=FALSE, message =FALSE,fig.height=4)
knitr::opts_chunk$set(fig.showtext=TRUE)
knitr::opts_chunk$set(fig.width=6.5, fig.height = 4, out.width = 6.5, out.height = 4)
knitr::opts_chunk$set(dev="png", dev.args=list(type="cairo", pointsize=36), dpi=300)

require(ggplot2)
require(dplyr)
```

## Example image

```{r highdpi}
dia = ggplot2::diamonds %>% filter(cut=="Ideal", clarity=="SI2", color!="J")
ggplot(dia, aes(x=carat, y=price)) + facet_wrap(~color) + geom_point() + theme_light(36)
```

输出结果

输出结果


我认为 DPI 与你的问题无关,我认为差异在于 theme_light(36)theme_light(16)。你的输出是这些主题选项下图形窗口中交互会话中显示的方式。 - Gregor Thomas
这些图像来自渲染的 Word 文档,而不是交互式会话。 - tkerwin
是的,如果您只在交互式会话中运行绘图代码而不使用您的块选项和dpi,则会获得类似的图像。因此dpi不是问题。问题在于第一个使用了theme_light(36),而第二个则更改为theme_light(16) - Gregor Thomas
好的,但我的问题是如何在不使分面包装标签周围出现巨大边距的情况下增加字体大小?我会重新措辞我的问题。 - tkerwin
theme(strip.text.x = element_text(margin = margin(b = 0, t = 0) ) ) 这样写可以达到你想要的效果吗? - aosmith
是的!似乎直接设置strip.text.x可以工作,而设置strip.text则不行。请将您的解决方案添加为答案。 - tkerwin
1个回答

6
ggplot2_2.2.1 中,您可以使用 strip.text.x 并搭配 margin 来更改条纹的边距。(在开发版本中,您也可以直接使用 strip.text 来实现这一点。)
下面是我将顶部和底部边距设置为 0 的例子:
ggplot(dia, aes(x=carat, y=price)) + 
     facet_wrap(~color) + 
     geom_point() + 
     theme_light(36) +
     theme(strip.text.x = element_text( margin = margin( b = 0, t = 0) ) )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接