How to change legend font color in ggplot2

51 Views Asked by At

Does anyone know how to change ggplot2 legend font colors using a character vector? I tried the ggtext package, subbing element_text() for element_markdown(). No luck. Thanks.

library(ggplot2)

library(ggtext)

woof <- qplot(wt, mpg, data = mtcars, colour = factor(cyl))

co <- c("red","blue","green")

woof2 <- woof + theme(axis.text=element_blank()) + theme(legend.text=element_markdown(color=co, size=12))



woof2

enter image description here

1

There are 1 best solutions below

0
jared_mamrot On

One potential option is to specify the label color in scale_color_manual() then render it using element_markdown(), e.g.

library(tidyverse)
library(ggtext)

co <- c("red","blue","green")
qplot(wt, mpg, data = mtcars, colour = factor(cyl)) +
  theme(axis.text=element_blank()) +
  theme(legend.text=element_markdown(size=12)) +
  scale_color_manual(labels = paste("<span style='color:",
                                   co,
                                   "'>",
                                   c(4,6,8),
                                   "</span>"),
                    values = co)
#> Warning: `qplot()` was deprecated in ggplot2 3.4.0.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
#> generated.

Created on 2023-09-20 with reprex v2.0.2

Would that work for your use-case?