Andrei_we
Andrei_we

Reputation: 45

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")

Upvotes: 2

Views: 789

Answers (2)

teunbrand
teunbrand

Reputation: 37933

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)

Upvotes: 2

stefan
stefan

Reputation: 124148

One option to achieve your desired result would be to make use of the ggtext package which allows styling of text labels and theme elements via markdown and/or HTML.

Making use of mtcars as example dataset:

library(ggplot2)
library(ggtext)

mtcars2 <- mtcars
mtcars2$cyl <- paste("<span style='color: royalblue3'>", mtcars2$cyl, "</span>")
mtcars2$am <- paste("<span style='color: black'>", mtcars2$am, "</span>")
ggplot(mtcars2, aes(hp, mpg)) +
  geom_point() +
  facet_wrap(cyl~am) +
  theme(strip.text = ggtext::element_markdown(size = 11))

Upvotes: 1

Related Questions