Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit distance between the facet / strip and the plot

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

like image 838
Feng Tian Avatar asked Apr 13 '19 04:04

Feng Tian


2 Answers

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

like image 123
pogibas Avatar answered Nov 09 '22 17:11

pogibas


There is a much simpler solution

theme(strip.placement = "outside")
like image 34
Joshua Avatar answered Nov 09 '22 17:11

Joshua