Skip to content

Instantly share code, notes, and snippets.

@wckdouglas
Created February 1, 2017 20:53
Show Gist options
  • Save wckdouglas/e6e99153fc6d6e784e8ff0474c5274ca to your computer and use it in GitHub Desktop.
Save wckdouglas/e6e99153fc6d6e784e8ff0474c5274ca to your computer and use it in GitHub Desktop.
Given a ggplot2 plot, matching colors on legend text with the keys
library(grid)
# http://stackoverflow.com/questions/23588127/match-legend-text-color-in-geom-text-to-symbol
coloring_legend_text <- function(p){
g <- ggplotGrob(p)
names.grobs <- grid.ls(grid.force(g))$name
labels <- names.grobs[which(grepl("label", names.grobs))]
# Get the colours
# The colours are the same as the colours of the plotted points.
# These are available in the ggplot build data.
gt <- ggplot_build(p)
colours <- unique(gt$data[[1]][, "colour"])
# Edit the 'label' grobs - change their colours
# Use the `editGrob` function
for(i in seq_along(labels)) {
g <- editGrob(grid.force(g), gPath(labels[i]), grep = TRUE,
gp = gpar(col = colours[i]))
}
#Draw it
grid.newpage()
grid.draw(g)
return(g)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment