I am trying to annotate a line plot with an arrow pointing to the highest point in line plot and displaying an arrow and maximum value on the plot. I am using the mtcars
dataset as my reference. Below is my code.
e <- df$mpg
ggplot(df, aes(x=e, y=df$hp)) +
geom_line() +
annotate("segment", color="blue", x=max(e), xend = max(e), y=max(df$hp),
yend=max(df$hp), arrow=arrow())
Thanks in advance,
Are you looking for something like this:
Explanation: In order to annotate with the max, we need to find the position of mpg that is the maximum for hp. To do this we use
mtcars[which(mtcars$hp == max(mtcars$hp)), "mpg"]
. Thewhich()
statement gives us the row possition of that maximum so that we can get the correct value of mpg. Next we annotate with this position adding a little bit of space (i.e., the +2 and +.2) so that it looks nicer. Lastly, we can construct a dataframe with the same positions (but different offset) and usegeom_text()
to add the data label.