0

Consider the two following examples:

ggplot(mtcars, aes(x = wt, y = qsec)) +
  geom_point() +
  facet_grid(cols = vars(vs), rows = vars(gear), scales = "free") +
  geom_vline(aes(xintercept = mean(wt)))

enter image description here

Notice how this produces the same values of xintercept for geom_vline in the same column, even with scales = "free" as was explained in this question. As suggested there, I should use facet_wrap instead of facet_grid. Notice, however, that the labels of one faceting variable are on the top of the graph, while the other ones are on the right. If we try it in a different way:

ggplot(mtcars, aes(x = wt, y = qsec)) +
  geom_point() +
  facet_wrap(facets = c("gear", "vs"), nrow = 3, ncol = 2, scales = "free") +
  geom_vline(aes(xintercept = mean(wt)))

enter image description here

We now get the xintercepts displayed separately in each facets. However, now the labels of both faceting variables are above the graphs. How do I move them so that, like in the facet_grid, one variable's labels are on top and one on the right? I tried using strip.position = c("top", "right") in facet_wrap, but that gives the following error:

Error in match.arg(strip.position, c("top", "bottom", "left", "right")) : 
  'arg' must be of length 1

So then how to do it?

J. Doe
  • 1,544
  • 1
  • 11
  • 26

1 Answers1

2

Adapted from https://stackoverflow.com/a/72556059/6851825

I don't think there is a simple way to do this with ggplot2 alone, since the facet_grid layout doesn't allow you to change the ranges for every facet independently.

ggplot(mtcars, aes(x = wt, y = qsec)) +
  geom_point() +
  ggh4x::facet_grid2(gear ~ vs, scales = "free", axes = "x", independent = "all") +
  geom_vline(aes(xintercept = mean(wt)))

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53