r - Make geom_text colour darker than geom_point colour -


i labeling scatter plot values. make readable, want text colour darker points (a green point have darker green label):

p1 <- ggplot(iris, aes(sepal.length, sepal.width, col = species))+   geom_point()+   geom_text(aes(label = sepal.length), size = 2, position = position_dodge(width = 0.2)) 

i can use scale_colour_discrete create effect want, applies both points , text.

p1 + scale_colour_discrete(l = 50) 

can apply text only?

you can try:

# specify colour col <- c("red", "blue", "green") p1 <- ggplot(iris, aes(sepal.length, sepal.width, col = species))+       geom_point() p1 <- p1 + scale_colour_manual(values = col) 

now darken colour using col2rgb , rgb (source) or approach

col2 <- col2rgb(col) col2 <- col2/2  # can use of course other values 2. higher values darker output. col2 <- rgb(t(col2), maxcolorvalue=255) 

plot labels.

p1  + geom_text(aes(label = sepal.length), col=factor(iris$species, labels=col2), size = 2, position = position_dodge(width = 0.2)) 

for better overview recommend use geom_text_repel. of note, have use as.character.

require(ggrepel) p1 +   geom_text_repel(aes(label = sepal.length), size = 2, col= as.character(factor(iris$species, labels=col2))) 

enter image description here

if don't want specify colour in beginning can extract original ggplot colors using:

g <- ggplot_build(p1) col <- unlist(unique(g$data[[1]]["colour"])) 

then use code above darker text colour or combine in darker function:

p1 <- ggplot(iris, aes(sepal.length, sepal.width, col = species))+       geom_point() # function  darken <- function(plot, factor=1.4){   g <- ggplot_build(plot)   color <- unlist((g$data[[1]]["colour"]))   col <- col2rgb(color)   col <- col/factor   col <- rgb(t(col), maxcolorvalue=255)   col }  # basic text p1  + geom_text(aes(label = sepal.length), col=darken(p1, 2), size = 2, position = position_dodge(width = 0.2)) # repel text p1  + geom_text_repel(aes(label = sepal.length), col= darken(p1, 2), size = 2) 

Comments