Open4

ggplot2::facet_wrap/_gridのTips

yuuyuu

facet wrapでfacet毎に軸のラベルを変える方法

labels_fun <- function(x) {
  if (max(x, na.rm = TRUE) <= 1) {
    scales::percent(x)      
  } else {
    scales::comma(x)
  }
}

d <- expand.grid(
  yr = 2020:2025,
  gender = c("Male", "Femal"),
  quant = c("num", "per"),
  index = c("kpi-1", "kpi-2")
) %>% 
  mutate(
    value = if_else(quant == "num", runif(n(), 1000, 10000), runif(n(), 0, 1))
  ) %>% 
  arrange(yr, gender, quant)

d %>% 
  ggplot(aes(x = yr, y = value, group = gender, color = gender)) +
  geom_line() +
  facet_grid(rows = vars(quant), cols = vars(index), scale = "free_y") +
  scale_y_continuous(labels = labels_fun)

yuuyuu

facetのラベルの色を変える方法

library(ggtext)
d <- expand.grid(
  yr = 2020:2025,
  gender = c("Male", "Female"),
  quant = c("num", "per"),
  index = c("kpi-1", "kpi-2")
  ) %>% 
  mutate(
    value = if_else(quant == "num", runif(n(), 1000, 10000), runif(n(), 0, 1))
  ) %>% 
  mutate(
    facet_key_index = case_when(
      index == "kpi-1"  ~ paste0("<span style='color:", "#1f497d", "'>kpi-1</span>"),
      index == "kpi-2" ~ paste0("<span style='color:",  "#e4ba66", "'>kpi-2</span>"),
    ),
    facet_key_kpi = factor(facet_key_index, levels = c(
      paste0("<span style='color:", "#1f497d", "'>kpi-1</span>"), 
      paste0("<span style='color:", "#e4ba66",  "'>kpi-2</span>")
    )),
    facet_key_gender = case_when(
      gender == "Male"  ~ paste0("<span style='color:", "darkblue", "'>Male</span>"),
      gender == "Female" ~ paste0("<span style='color:",  "tomato",   "'>Female</span>"),
    )
  ) %>% 
  filter(quant == "num")

d %>% 
  ggplot(aes(x = yr, y = value, group = quant)) +
  geom_line() +
  facet_grid(rows = vars(facet_key_gender), cols = vars(facet_key_index)) +
  theme(strip.text = element_markdown(face = "bold", size = rel(1.4)))

yuuyuu

facetのbackgroundの色を変える方法

library(gghx)
ridiculous_strips <- strip_themed(
     # Horizontal strips
     background_x = elem_list_rect(fill = c("limegreen", "dodgerblue")),
     text_x = elem_list_text(colour = c("dodgerblue", "limegreen"),
                             face = c("bold", "bold")),
     by_layer_x = TRUE,
     # Vertical strips
     background_y = elem_list_rect(
       fill = c("gold", "tomato", "deepskyblue")
     ),
     text_y = elem_list_text(angle = c(0, 90)),
     by_layer_y = FALSE
)

p + facet_grid2(class ~ drv + year, strip = ridiculous_strips)

参考)

yuuyuu

facetのボックスをラウンドボックスにする方法

library(ggtext)
ggplot(mpg, aes(cty, hwy)) + 
  geom_point() +
  facet_wrap(~class) +
  theme(
    strip.background = element_blank(),
    strip.text = element_textbox(
      size = 12,
      color = "white", fill = "#5D729D", box.color = "#4A618C",
      halign = 0.5, 
      linetype = 1, 
      r = unit(8, "pt"), 
      width = unit(0.75, "npc"),
      padding = margin(2, 0, 1, 0), margin = margin(3, 3, 3, 3)
    )
  )

参考文献)