Search code examples
rggplot2visualizationfacetggthemes

Changing colour of strip.text using facet_wrap of 2 variables


Please see picture below and focus on the strip text in blue (left upper side of each graph).

plot of producción of something

As I used facet_wrap on 2 variables, I would like that the bottom strip text is coloured black while the top strip text maintains its royalblue3 colour.

I tried to use ggthemes, strip.text.x / strip.text.y options but could not find out how to do this.

Here is the code:

    ggplot(aes(Año, Valor, group = DEPP, color = DEPP)) +
  geom_line(size  = 1,
            alpha = 0.6 ) +
  geom_point(shape = 22, 
             size = 1.5, 
             fill = "grey") +
  theme_ipsum() +
  scale_y_continuous(labels = unit_format(unit = "S/", scale = 1)) +
  scale_x_discrete(breaks = c(2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021)) +
  theme(axis.title.y = element_blank(), 
        axis.title.x = element_blank()) + # Delete the title of the y and x axis
  labs(
    title = "Evolución Valor del Volumen de Producción Según Estado del Pescado y Órigen",      
    subtitle = "Valor de volumen (Kg equivalentes) registrado por la respectiva Dirección de Extracción y Procesamiento Pesquero (DEPP)",
    caption = "Fuente: DIREPRO"
  ) +
  guides(color = "none") +
  facet_wrap(DEPP ~reorder(EstadoPescado, -Valor), scales = "free_y", ncol = 3) +
  theme(strip.text.x = element_text(size = 11, colour = "royalblue3")) #Using ggthemes

  ggsave("desembarque_plot.png", 
         path = here("figures"), 
         width = 15*3, height = 8*10, 
         units = "cm")

Solution

  • I'm experimenting with custom strips over at the github version of ggh4x. The feature isn't on CRAN yet, but you might find it useful. The main idea is that you can give a list of elements to a strip. Blatantly riffing off stefan's example:

    library(ggplot2)
    library(ggh4x) # devtools::install_github("teunbrand/ggh4x")
    
    ggplot(mtcars, aes(hp, mpg)) +
      geom_point() +
      facet_wrap2(
        cyl~am,
        strip = strip_themed(
          text_x = elem_list_text(colour = c("royalblue3", "black")),
          by_layer_x = TRUE
        )
      )
    

    Created on 2021-08-04 by the reprex package (v1.0.0)

    (obligatory disclaimer: I'm the author ggh4x. If you find any bugs, it's a great time to report them)