How to highlight geom_text in ggplot that matches certain text

Viewed 456

I want to highlight a certain text in a ggplot scatterplot. The code I have is here

library(ggplot2)

labels <- c("green", "blue", "orange", "blue", "green","red","purple","black")
num_1 <- c(1,2,3,4,5,6,7,8)
num_2 <- c(5,9,3,7,4,3,1,8)
df <- data.frame(labels,num_1,num_2)

p <- ggplot(df, aes(num_1,num_2,label=labels)) + geom_text() 
p

For example, I want to highlight the text "green" by changing its font to bold or changing its color to yellow. Either works but I haven't been able to get it working. I've tried using gghighlight but haven't found a way to get it to work.

1 Answers

All three of your suggestions work. Using gghighlight, you have to set a predicate for what datapoints you want to highlight:

library(ggplot2)

labels <- c("green", "blue", "orange", "blue", "green","red","purple","black")
num_1 <- c(1,2,3,4,5,6,7,8)
num_2 <- c(5,9,3,7,4,3,1,8)
df <- data.frame(labels,num_1,num_2)

ggplot(df, aes(num_1,num_2,label=labels)) + 
  geom_text() +
  gghighlight::gghighlight(labels == "green")
#> Warning: Tried to calculate with group_by(), but the calculation failed.
#> Falling back to ungrouped filter operation...

If you want to stay in vanilla ggplot2, you can simply use an ifelse() in the aes() function:

ggplot(df, aes(num_1, num_2, label= labels)) +
  geom_text(aes(fontface = ifelse(labels == "green", "bold", "plain")))

If you want to set colours directly, without mapping them to a scale first, you can use the I() function to use the identity scale that does not map/transform the data.

ggplot(df, aes(num_1, num_2, label= labels)) +
  geom_text(aes(colour = I(ifelse(labels == "green", "yellow", "black"))))

Created on 2021-04-16 by the reprex package (v1.0.0)

Related