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)))
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)))
We now get the xintercept
s 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?
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)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.