Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

New ways to change the text color of strip text in facet_wrap (ggplot2)?

This question has been asked and answered a few times – most recently here – but are a few years old, involve a for-loop and grid, and are a bit hacky. I was wondering if there were any new ways to change the color of my strip text to match the title text, preferably within ggplot.

library(ggplot2)
library(ggtext)

facet_colors <- c("#43A047","#8A2BE2", "#007ACC")

iris |>
  pivot_longer(-Species) |>
  ggplot(aes(x = name,
             y = value, 
             # group = Species,
             fill = Species)) +
  geom_boxplot() +
  scale_fill_manual(values = facet_colors) +
  labs(title ="Feature Comparison of <span style = 'color: #43A047;'>Setosa</span>, 
       <span style = 'color: #8A2BE2;'>Versicolor</span> and 
       <span style = 'color: #007ACC;'>Virginica</span>") +
  facet_wrap(~Species) +
  theme_minimal() +
  theme(plot.title = element_markdown())

faceted ggplot

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As you are already using ggtext, basically the same approach applies to the strip text, e.g. using a labeller() function and setting strip.text=element_markdown() too you could do:

library(ggplot2)
library(ggtext)

facet_colors <- c("#43A047", "#8A2BE2", "#007ACC")

iris |>
  tidyr::pivot_longer(-Species) |>
  ggplot(aes(
    x = name,
    y = value,
    fill = Species
  )) +
  geom_boxplot() +
  scale_fill_manual(values = facet_colors) +
  labs(title = "Feature Comparison of <span style = 'color: #43A047;'>Setosa</span>,
       <span style = 'color: #8A2BE2;'>Versicolor</span> and
       <span style = 'color: #007ACC;'>Virginica</span>") +
  facet_wrap(~Species,
    labeller = labeller(
      Species = c(
        virginica = "<span style = 'color: #007ACC;'>Virginica</span>",
        versicolor = "<span style = 'color: #8A2BE2;'>Versicolor</span>",
        setosa = "<span style = 'color: #43A047;'>Setosa</span>"
      )
    )
  ) +
  theme_minimal() +
  theme(
    plot.title = element_markdown(),
    strip.text = element_markdown()
  )

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading