0

In my plot I would like to alter both the color of the points and the color of the labels on those points. I can control the color of points and labels independently, but in the same plot this breaks down. I have provided code for all three scenarios.

library(dplyr)
library(ggplot2)

ds <- 
  mtcars %>% 
  count(cyl, vs) %>% 
  mutate(
    label_color = case_when(
      n > median(n) ~ "black",
      TRUE ~ "white")
  ) 

# Works
ds %>% 
  ggplot(aes(x = as.character(vs), y = cyl, size = n, color = n, label = n)) + 
  geom_point() + 
  geom_text(aes(color = label_color)) + 
  scale_color_identity() #+
  #scale_color_gradient(low = "red", high = "blue") 

# Works
ds %>% 
  ggplot(aes(x = as.character(vs), y = cyl, size = n, color = n, label = n)) + 
  geom_point() + 
  geom_text(aes(color = label_color)) + 
  #scale_color_identity() +
  scale_color_gradient(low = "red", high = "blue") 

# Fails
ds %>% 
  ggplot(aes(x = as.character(vs), y = cyl, size = n, color = n, label = n)) + 
  geom_point() + 
  geom_text(aes(color = label_color)) + 
  scale_color_identity() +
  scale_color_gradient(low = "red", high = "blue") 
Joe
  • 3,217
  • 3
  • 21
  • 37
  • 1
    In ggplot you can only have one color= scale. You can use color and fill separately https://stackoverflow.com/questions/18347147/using-two-scale-colour-gradients-ggplot2. Maybe check this out https://rpubs.com/almartin/two_scales – MrFlick Aug 01 '18 at 21:11
  • 1
    You can't really have two color scales like this. This is a case you could get away with passing the vectors of color outside `aes()` for `geom_text()`: `geom_text(color = ds$label_color)`. Otherwise I'd use the `color` and `fill` trick as mentioned in another comment. – aosmith Aug 01 '18 at 21:12

0 Answers0