Make the geom_text color darker than the geom_point color

I put a scatter plot with values. To make it readable, I want the text to be darker than the dots (the green dot would have a 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 to create the effect I want, but it applies to both points and text.

p1 + scale_colour_discrete(l = 50)

Is it possible to apply it only to the text?

+4
source share
2 answers

You can try:

# specify your 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 your color using col2rgband rgb( source ) or another approach

COL2 <- col2rgb(COL)
COL2 <- COL2/2  # you can use of course other values than 2. Higher values the darker the output.
COL2 <- rgb(t(COL2), maxColorValue=255)

Mark the tags.

p1  + geom_text(aes(label = Sepal.Length), col=factor(iris$Species, labels=COL2), size = 2, position = position_dodge(width = 0.2))

geom_text_repel. , 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

, ggplot, :

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

:

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)
+1

:

n <- length(levels(iris$Species))
cols_points <- hcl(h = seq(15, 375, length = n + 1), l = 65, c = 100)[1:n]

, , :

p1 <- ggplot(iris, aes(Sepal.Length, Sepal.Width, colour = Species)) + geom_point() + scale_colour_manual(values = cols_points)

, , , (l, , ):

cols_text <- hcl(h = seq(15, 375, length = n + 1), l = 30, c = 100)[1:n]

iris_cols <- ifelse(iris$Species == "setosa", cols_text[1], 
                ifelse(iris$Species == "versicolor", cols_text[2], cols_text[3]))

( y, ):

p1 + annotate("text", x = iris$Sepal.Length, y = iris$Sepal.Width + 0.05, label = iris$Sepal.Length, color = iris_cols, size = 2)
+1

Source: https://habr.com/ru/post/1649778/


All Articles