Last active
February 13, 2022 22:58
-
-
Save jimjam-slam/8b1ca5848bc874ced893c0e5c241f88b to your computer and use it in GitHub Desktop.
Use case_when with geom_text to automatically label points that mmeet certain conditions (extrema, significance, etc.) #rstatstips
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
library(ggrepel) # substitude geom_text for geom_text_repel if you don't want to bother with this! | |
mydata = | |
data_frame( | |
x = 1:10, | |
y = rnorm(10), | |
name = c('Apple', 'Banana', 'Kiwi', 'Orange', 'Watermelon', | |
'Grapes', 'Pear', 'Cantelope', 'Tomato', 'Satsauma')) %>% | |
mutate( | |
name_interesting = case_when( | |
y < 0 ~ name, # keep the labels for points you want to highlight | |
# you can add more criteria here! | |
TRUE ~ "")) # ditch the rest | |
ggplot(mydata, aes(x = x, y = y)) + | |
# note: both geoms inherit x and y aesthetics | |
geom_point(size = 5) + | |
geom_text_repel(aes(label = name_interesting), point.padding = 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Whoops! There was also also one missing on line 9 😅