Question

Is there a way to prevent facet labels from being equal width (after rotation)

When I apply a facet_grid, sometimes the labels are quite wide, sometimes so wide that they don't fit, and I have to rotate them. This isn't a problem unless I want to facet by multiple different groups. In this case, it auto-sizes every single group's label to be the same as the longest label. A reproducible example should help clarify my meaning:

library(tidyverse)

data<-diamonds |> mutate(cut=paste("Super Duper Long Description Which Demonstrates The Issue",cut))

data |> filter(str_detect(cut,"(Ideal|Premium|Good)") & clarity%in%c("SI1","SI2","VS1","VS2")) |>
  ggplot(aes(x=color,y=price)) +
  geom_boxplot() +
  facet_grid(cut+clarity~.) +
  theme(strip.text.y = element_text(angle=0,vjust=0.5))

Graph Output from above text

As you can see, the width of the longest label is applied to the "cut" strip as well.

In case it's not obvious, below is the desired output: Desired Output

Is there a method to prevent this from happening? Or is this a bug that should be reported upstream?

 4  58  4
1 Jan 1970

Solution

 3

One option to achieve your desired result would be to use ggh4x::facet_grid2 which using the strip= argument allows for strip text boxes of variable width or size:

library(tidyverse)
library(ggh4x)

data <- diamonds |>
  mutate(cut = paste("Super Duper Long Description Which Demonstrates The Issue", cut)) |>
  filter(
    str_detect(cut, "(Ideal|Premium|Good)") & clarity %in% c("SI1", "SI2", "VS1", "VS2")
  )


data |>
  ggplot(aes(x = color, y = price)) +
  geom_boxplot() +
  ggh4x::facet_grid2(cut + clarity ~ .,
    strip = ggh4x::strip_vanilla(size = "variable")
  ) +
  theme(
    strip.text.y = element_text(angle = 0, vjust = 0.5)
  )

2024-07-04
stefan