Search code examples
rggplot2annotationsggpmisc

How to annotate line plot with arrow and maximum value?


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,


Solution

  • Are you looking for something like this:

    labels <- data.frame(mpg = mtcars[which(mtcars$hp == max(mtcars$hp)), "mpg"]+7, hp = mtcars[which(mtcars$hp == max(mtcars$hp)), "hp"],text = paste0("Max value at mpg = ", mtcars[which(mtcars$hp == max(mtcars$hp)), "mpg"], " and hp = ", max(mtcars$hp)))
    
    
    ggplot(mtcars, aes(mpg, hp))+
        geom_line()+
        geom_text(data = labels, aes(label = text))+
        annotate("segment", 
            x=mtcars[which(mtcars$hp == max(mtcars$hp)), "mpg"]+2,
            xend=mtcars[which(mtcars$hp == max(mtcars$hp)), "mpg"]+.2, 
            y= mtcars[which(mtcars$hp == max(mtcars$hp)), "hp"],
            yend= mtcars[which(mtcars$hp == max(mtcars$hp)), "hp"], 
            arrow=arrow(), color = "blue")
    

    enter image description here

    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"]. The which() 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 use geom_text() to add the data label.