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) |
Whoops! There was also also one missing on line 9 😅
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi James,
thanks for the text version of the code in GIT.
I believe the GIT plain text code example
is missing an extra closing parenthesis
(shown below in bold),
in 2 places:
line 14: TRUE ~ ""))
line 16: y = y) ) +
I may be wrong, of course, :-)
SF99
San Francisco