Reputation: 4949
is there a way to add text next to a point only if a value is met? For example I have here,
library(ggplot2)
library(ggrepel)
x = c(0.8846, 1.1554, 0.9317, 0.9703, 0.9053, 0.9454, 1.0146, 0.9012,
0.9055, 1.3307)
y = c(0.9828, 1.0329, 0.931, 1.3794, 0.9273, 0.9605, 1.0259, 0.9542,
0.9717, 0.9357)
z= c("a", "b", "c", "d", "e", "f",
"g", "h", "i", "j")
df <- data.frame(x = x, y = y, z = z)
ggplot(data = df, aes(x = x, y = y)) + theme_bw() +
geom_text_repel(aes(label = z),
box.padding = unit(0.45, "lines")) +
geom_point(colour = "green", size = 3)
This will give me something that looks like this.
however what if I only want the text to appear if y > 1.3 in this case only "d" will be labeled. Any ideas? thanks in advance.
Upvotes: 0
Views: 2426
Reputation: 10761
If you specify the data
within the geom_text_repel
call:
ggplot(data = df, aes(x = x, y = y)) + theme_bw() +
geom_text_repel(data = df[which(df$y > 1.3),],
aes(label = z),
box.padding = unit(0.45, "lines")) +
geom_point(colour = "green", size = 3)
Upvotes: 1
Reputation: 20746
Subset the data within the geom_text_repel
parameter.
e.g.
library(ggplot2)
library(ggrepel)
x = c(0.8846, 1.1554, 0.9317, 0.9703, 0.9053, 0.9454, 1.0146, 0.9012,
0.9055, 1.3307)
y = c(0.9828, 1.0329, 0.931, 1.3794, 0.9273, 0.9605, 1.0259, 0.9542,
0.9717, 0.9357)
z= c("a", "b", "c", "d", "e", "f",
"g", "h", "i", "j")
df = data.frame(x = x, y = y, z = z)
ggplot(data = df, aes(x = x, y = y)) + theme_bw() +
# Subset the data as it relates to the y value
geom_text_repel(data = subset(df, y > 1.3), aes(label = z),
box.padding = unit(0.45, "lines")) +
geom_point(colour = "green", size = 3)
Upvotes: 3