当我应用facet_grid时,有时标签很宽,有时太宽以至于不适合,我必须旋转它们。这不是问题,除非我想面对多个不同的群体。在这种情况下,它会自动调整每个组标签的大小,使其与最长标签相同。一个可重现的例子应该有助于澄清我的意思:
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))
如您所见,最长标签的宽度也应用于“切割”条带。
有没有办法防止这种情况发生?或者这是一个应该向上游报告的错误?
实现所需结果的一个选项是使用
ggh4x::facet_grid2
,它使用 strip=
参数允许条带可变宽度或大小的文本框:
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)
)