Rspacer
Rspacer

Reputation: 2429

How to change text colour of facet_grid label in ggplot2 R?

How can I change the black facet labels (A and B) into the color of factors (A and B) red and blue respectively ? There are plenty of examples on how to change the background label colour but not the text color.

library(data.table)
A = data.table(x = 1:4, y = 1:4, z = c('A','A','B','B'))

ggplot(A) + geom_point(aes(x = x, y = y, color = z)) + facet_grid(~z) + theme_bw()

enter image description here

Upvotes: 1

Views: 242

Answers (1)

stefan
stefan

Reputation: 123783

One option to achieve your desired result would be via the ggtext package which via element_markdown allows to style theme elements via HTML, CSS and markdown:

library(ggplot2)
library(ggtext)

cols <- data.frame(
  z = c("A", "B"),
  color = scales::hue_pal()(2)
)

A <- merge(A, cols, by = "z", all.x = TRUE)
A$facet <- paste0("<span style='color: ", A$color, "'>", A$z, "</span>")

ggplot(A) + 
  geom_point(aes(x = x, y = y, color = z)) + 
  facet_grid(~facet) + 
  theme_bw() +
  theme(strip.text.x = ggtext::element_markdown(face = "bold"))

Upvotes: 3

Related Questions