1

How do you colorize the values of the legend value labels (currently in gray) to match exactly the colors of the points of the scatter plot?

library(ggplot2)
ggplot(diamonds, aes(x=carat, y=price, col=cut)) + 
  geom_point()

enter image description here

user115916
  • 186
  • 11

1 Answers1

3

To color the legend text labels according to the points I would suggest to use a named color vector and some styling via HTML/CSS using ggtext inside a scale_color_manual:

library(ggplot2)
library(ggtext)

pal_viridis5 <- scales::viridis_pal()(5)
names(pal_viridis5) <- levels(diamonds$cut)

ggplot(diamonds, aes(x = carat, y = price, col = cut)) +
  geom_point() +
  scale_color_manual(
    values = pal_viridis5,
    labels = ~ paste0("<span style='color: ", pal_viridis5[.x], "'>", .x, "</span>")
  ) +
  theme(legend.text = ggtext::element_markdown())

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51