Home > Back-end >  ggplot label color based on condition
ggplot label color based on condition

Time:05-04

I am attempting to change the color geom_label_repel based on a condition. For example:

res <- data.frame(group = c("Group 1", "Group 2", "Group 3", "Group 4", "Group 5"),
                 correlation = c(0.37,0.33,0.31,0.30,0.30))
res <- res %>%
  arrange(desc(correlation))

res

  group correlation
1 Group 1        0.37
2 Group 2        0.33
3 Group 3        0.31
4 Group 4        0.30
5 Group 5        0.30

I want to label the three groups with the highest correlation value. Then I want to change the color of the point with the highest correlation value if the difference between the subsequent group is > 0.03. My code right now gives me this plot

p <- res %>%
  ggplot(aes(x = reorder(group, -correlation), y = correlation))  
  geom_point()  
  geom_label_repel(data = slice_max(res, n = 3, correlation),
                   aes(label = group))

enter image description here

Now, I want to change the color of the Group 1 label because its correlation value is > 0.03 than Group 2's correlation. Any help would be appreciated

CodePudding user response:

We could do this by adding a helper column based on the condition:

library(tidyverse); library(ggrepel)
res <- res %>%
  arrange(desc(correlation)) %>%
  mutate(my_col = if_else(
    row_number() == 1 & correlation > lead(correlation)   0.03,
    "highlight",
    "other"
  )) 


res %>%
  ggplot(aes(x = group, y = correlation, color = my_col))  
  geom_point()  
  geom_label_repel(data = slice_max(res, n = 3, correlation),
                   aes(label = group))  
  scale_color_manual(values = c("highlight" = "red", "other" = "black"))  
  guides(color = "none")    # optional, hides legend

enter image description here

  • Related