I am wondering if there is an effective way to map data to the legend text color in ggplot2, just as we can do with axis text. The following is an example of reproducibility.
First, let's plot:
library(ggplot2) library(dplyr) drv_counts <- mutate(mpg, drv = case_when(drv == "r" ~ "rear wheel drive", drv == "4" ~ "4 wheel drive", drv == "f" ~ "front wheel drive"), model_drv = interaction(model, drv)) %>% group_by(model_drv) %>% summarize(model = model[1], drv = drv[1], count = n()) %>% arrange(drv, count) %>% mutate(model = factor(model, levels = model)) p <- ggplot(drv_counts, aes(x=model, y=count, fill=drv)) + geom_col() + coord_flip() + guides(fill = guide_legend(reverse=T)) + theme_minimal() p

Now give the color of the axis labels to the transport. It is very simple:
# ggplot2 colors cols <- c("4 wheel drive" = "#F8766D", "front wheel drive" = "#00BA38", "rear wheel drive" = "#619CFF") p2 <- p + theme(axis.text.y = element_text(color = cols[drv_counts$drv])) p2

Now try the same trick in the legend. This does not work:
p2 + theme(legend.text = element_text(color = cols))

The reason this doesn't work for legend text but works for axis text is because all axis labels are drawn in one grob, and so we can give that grob a color vector, but legend labels are drawn in separate rodents.
We can go and color all the vultures by hand, but this is super ugly and bulky:
g <- ggplotGrob(p2) g$grobs[[15]]$grobs[[1]]$grobs[[9]]$children[[1]]$gp$col <- cols[g$grobs[[15]]$grobs[[1]]$grobs[[9]]$children[[1]]$label] g$grobs[[15]]$grobs[[1]]$grobs[[10]]$children[[1]]$gp$col <- cols[g$grobs[[15]]$grobs[[1]]$grobs[[10]]$children[[1]]$label] g$grobs[[15]]$grobs[[1]]$grobs[[11]]$children[[1]]$gp$col <- cols[g$grobs[[15]]$grobs[[1]]$grobs[[11]]$children[[1]]$label] grid::grid.newpage() grid::grid.draw(g)

My question is: can anyone think of a way to get this effect without having to dig into the grotto? I am OK with the patch for ggplot2, if it is only a few modified lines. Alternatively, is it possible to automate digging in the grob tree, so I donβt need to access child oppressions by manually setting indexes of lists that will change the moment I make a slight change in my figure?
Update: A related question can be found here. To make my question different, add a requirement so that colors are not copied than characters, but can be set to any arbitrary values. This added requirement has real relevance, because I usually use a darker color for text than for characters.