tkerwin
tkerwin

Reputation: 9759

Margins for ggplot2 facet labels much too large when using high font size

When increasing font size to compensate for high dpi rendering in rmarkdown, the labels for the facet wrap ggplot image have an unusually large margin. In the example below, the vertical space above 'D', 'E', etc. is what I am trying to lower. I have tried changed the element_text margin as well as the panel.spacing theme parameter. Setting those to zero does not change things much.

Code

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

Output

Output

Upvotes: 5

Views: 4396

Answers (1)

aosmith
aosmith

Reputation: 36086

In ggplot2_2.2.1 you can use strip.text.x to change the margins of the strips with margin. (In the development version you may be be able to do this directly with strip.text).

Here I make the top and bottom margins 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) ) )

Upvotes: 7

Related Questions