Reputation: 35
If I have multiple factors in a facet_grid (something like facet_grid(cyl ~ am + vs)
, is it possible to wrap text from just one of them (just am
and not vs
)? Let's use the MTCARS df as an example, but instead of 0s and 1s for am
, imagine I have very long labels. :
mtcars2 <- mtcars
mtcars2$am <- factor(mtcars2$am,
levels = c(0,1),
labels = c("this is a very very very looooooooooooong label",
"this is also a very very very looooooooooooong label"))
ggplot(mtcars2, aes(wt,mpg)) +
geom_point() +
facet_grid(cyl ~ am + vs)
I can wrap that variable using labeller = label_wrap_gen()
, which increases the height of that box rather substantially (mostly fine with that), but the height of the box containing vs
is the same height as the new height for am
. Because my second factor is small (0/1), it doesn't need to be the same height as that of the first factor.
In my actual dataset, my plot is a 7 x 6 grid, and my labels wrap to like 6 lines (they aren't all that long, really, it's just that there are so many boxes, the width of each individual plot is much narrower, so, I need all space I can get to make this look ok.
Upvotes: 1
Views: 1099
Reputation: 38053
I don't know about specifically wrapping one of the labels, but the ggh4x package has some additional options for strips that sound appropriate for some other parts of your question.
Let's first edit the example to actually show the problem you're encountering. In the plot below, you can see that the Yes/No labels are given too much space relative to their size.
library(ggplot2)
df <- mtcars
df <- transform(
df,
am = ifelse(am, "I'm a label that is too long",
"I'm an even longer label that exceeds strip boundaries"),
vs = ifelse(vs, "Yes", "No")
)
p <- ggplot(df, aes(wt, mpg)) +
geom_point()
p + facet_grid(cyl ~ am + vs, labeller = label_wrap_gen())
The facets in ggh4x accept a strip
argument (more info here) that you can use to trim the excess space, but also to set one of the layers to use bold text instead of plain text.
library(ggh4x)
#> Warning: package 'ggh4x' was built under R version 4.1.1
p + facet_grid2(
cyl ~ am + vs, labeller = label_wrap_gen(),
strip = strip_themed(
size = "variable", # Shrinks 2nd layer
text_x = elem_list_text(face = c(1, 2)), # 2nd layer in bold
by_layer_x = TRUE
))
Created on 2021-12-10 by the reprex package (v2.0.0)
Disclaimer: I'm the author of ggh4x
Upvotes: 1