I am looking to add a single point to my ggplot geom_line at a specific x-value. The x-value where I want the point to fall does not have an associated y-value in the data frame; however, I want the point to fall on the line.
df <- mtcars
ggplot(df,aes(disp,wt)) +
geom_line() +
geom_point() +
geom_point(aes(x=200),color="red")
Ideally, I will only have one red point at x=200 and the point will fall on the ggplot geom_line(). Any information on how to do this is greatly appreciated–thank you!
>Solution :
You can use approx to find the y-value. And I’d recommend using annotate() instead of a geom_* function to add one-offs to a graph.
ggplot(df, aes(disp,wt)) +
geom_line() +
geom_point() +
annotate(
geom = "point",
x = 200,
y = approx(x = df$disp, y = df$wt, xout = 200)$y,
color="red"
)
