Skip to content

Instantly share code, notes, and snippets.

@jimjam-slam
Last active February 13, 2022 22:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimjam-slam/8b1ca5848bc874ced893c0e5c241f88b to your computer and use it in GitHub Desktop.
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
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)
@sfd99
Copy link

sfd99 commented Mar 22, 2018

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

@jimjam-slam
Copy link
Author

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