I'm trying to get a plot that shows some important data points highlighted.
Dataset:
df <- structure(list(its = 1:20, pd = c(-0.521, -1.866, -0.11, 0.296,
-0.14, -0.303, 0.141, 0.181, -0.116, 0.475, -0.117, 0.135, -0.139,
-0.062, -0.098, 1.601, -0.093, -1.993, 2.249, 0.48)), class = "data.frame", row.names = c(NA, -20L))
Plotting:
ggplot(df, aes(x = its, y = pd)) +
geom_point(size = 2, shape = 1) +
geom_hline(yintercept = c(-1.5, 1.5)) +
theme_bw() +
labs(x = "", y = "")
scale_x_discrete(limits = factor(its))
I get the plot below.
My goal is adding labels to multiple data points based on a condition (pd < -1.5 or pd > 1.5).
So, the desired result is below (notice: labels are not only come from its
vector. I also want to add I
to them).
Tyr geom_label
, with a filtered data argument and nudging.
library(gpglot2)
library(dplyr)
ggplot(df, aes(x = its, y = pd)) +
geom_point(size = 2, shape = 1) +
geom_hline(yintercept = c(-1.5, 1.5)) +
theme_bw() +
labs(x = "", y = "") +
geom_label(data=filter(df, pd < -1.5 | pd > 1.5),
aes(label=paste0("I", its)),
colour="red", nudge_x=0, nudge_y=0.2)