wilkelab / ggtext

Improved text rendering support for ggplot2
https://wilkelab.org/ggtext/
GNU General Public License v2.0
650 stars 37 forks source link

`element_textbox()` breaks for facet grid labels when switching positions #79

Closed jdtrat closed 9 months ago

jdtrat commented 2 years ago

Hiya! Thanks so much for such an incredible package. I use ggtext (and cowplot) on a regular basis! I ran into a problem keeping the coloring for facet labels when I use the switch argument in facet_grid() as outlined [here]. Do you know what might be causing this? Reprex below:

library(palmerpenguins)
library(ggplot2)
library(ggtext)

penguin_colors <- c("darkorange", "purple", "cyan4")

base_plot <- ggplot(penguins, 
                    aes(x = sex, y = flipper_length_mm, color = species)) +
  geom_point() +
  scale_color_manual(values = penguin_colors) +
  theme_classic() +
  theme(
    legend.position = "none",
    strip.background = element_blank(),
    strip.text.x = element_textbox(
      size = 16, face = "bold",
      color = "black", fill = "white", box.color = "black",
      halign = 0.5, linetype = 1, r = unit(5, "pt"), width = unit(1, "npc"),
      padding = margin(3, 0, 1, 0), margin = margin(3, 3, 3, 3)
    ),
    strip.text.y = element_textbox(
      size = 16, face = "bold",
      valign = 0.5,
      halign = 1, width = unit(0.2, "npc"),
      margin = margin(0, -25, 0, -30)
    ))

base_plot +
  facet_grid(species ~ island,
             scales = "free_y",
             labeller = labeller(
               .rows = as_labeller(~ glue::glue("<span style='color: {penguin_colors};'> {.x} </span>")),
               .cols = as_labeller(~ glue::glue("Island of {.x}"))
               )
             )
#> Warning: Removed 2 rows containing missing values (geom_point).

# Switching the axes to be on the left side removes the coloring
base_plot +
  facet_grid(species ~ island,
             scales = "free_y",
             switch = "y",
             labeller = labeller(
               .rows = as_labeller(~ glue::glue("<span style='color: {penguin_colors};'> {.x} </span>")),
               .cols = as_labeller(~ glue::glue("Island of {.x}"))
             )
  )
#> Warning: Removed 2 rows containing missing values (geom_point).

Created on 2022-02-26 by the reprex package (v2.0.1)

teunbrand commented 9 months ago

This can be fixed by setting the strip.text.y.left theme element. It's an issue of theme settings not inheriting the 'richer' element. See also https://github.com/tidyverse/ggplot2/issues/5457.

bwiernik commented 9 months ago

Yep this is a ggplot2 bug, so closing this here