Edit distance between the facet / strip and the plot
Asked Answered
C

3

6

For example,

library(ggplot2)
ggplot(mpg, aes(displ, cty)) + geom_point() + facet_grid(cols = vars(drv))

enter image description here How can I change the distance between the strip and the main plot? (For example, create a gap between the strip and the main plot.)
But I don't need to change the strip size (different from this edit strip size ggplot2).

Cambria answered 13/4, 2019 at 4:24 Comment(2)
I think you should specify theme(strip.background =...). See #14186254Harrovian
@Harrovian I need to create a gap between the strip and the main plot.Cambria
K
1

There is a much simpler solution

theme(strip.placement = "outside")
Kempf answered 20/12, 2019 at 16:31 Comment(0)
P
4

There can be multiple solutions to this problem.

geom_hline

A hacky one is to add a line (probably white, but it depends on your theme) on top of the plot. We can do this using geom_hline (or geom_vline if your facets are in rows). This creates an illusion of distance.

library(ggplot2)
ggplot(mpg, aes(displ, cty)) +
  geom_point() +
  facet_grid(cols = vars(drv)) +
  # Add white line on top (Inf) of the plot (ie, betweem plot and facet)
  geom_hline(yintercept = Inf, color = "white", size = 4) +
  labs(title = "geom_hline")

strip.background

Another solution (as suggested by @atsyplenkov) is to use theme(strip.background = ...). There you can specify color of the border. However, this is not a perfect as it cuts border from all the directions (there might be a way to improve this).

ggplot(mpg, aes(displ, cty)) +
  geom_point() +
  facet_grid(cols = vars(drv)) +
  # Increase size of the border
  theme(strip.background = element_rect(color = "white", size = 3)) +
  labs(title = "strip.background")

enter image description here

Pulver answered 13/4, 2019 at 10:8 Comment(0)
K
1

There is a much simpler solution

theme(strip.placement = "outside")
Kempf answered 20/12, 2019 at 16:31 Comment(0)
S
0

another yet simple option is to create "invisible" strips first and then adjust the text vertically:

    + theme(strip.background = element_rect(color = "white", fill = "white"),
            strip.text.x = element_text(vjust = 5)

In my case, I used it to reduce space between strip text and plot. But it should work vice versa.

Surface answered 30/6, 2023 at 6:33 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.