简体   繁体   English

如何用箭头和最大值注释线图?

[英]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. 我正在使用mtcars数据集作为参考。 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: 您是否正在寻找这样的东西:

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")

在此处输入图片说明

Explanation: In order to annotate with the max, we need to find the position of mpg that is the maximum for hp. 说明:为了注释最大值,我们需要找到mpg的位置,该位置是hp的最大值。 To do this we use mtcars[which(mtcars$hp == max(mtcars$hp)), "mpg"] . 为此,我们使用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. which()语句为我们提供了该最大值的行位置,以便我们可以获取mpg的正确值。 Next we annotate with this position adding a little bit of space (ie, the +2 and +.2) so that it looks nicer. 接下来,我们为该位置添加一点注释(即+2和+.2),以使其看起来更好。 Lastly, we can construct a dataframe with the same positions (but different offset) and use geom_text() to add the data label. 最后,我们可以构造一个具有相同位置(但偏移量不同)的数据geom_text()并使用geom_text()添加数据标签。

An alternative solution using packages 'ggpmisc' and 'ggrepel'. 使用软件包“ ggpmisc”和“ ggrepel”的替代解决方案。 (This code can be easily modified for tagging more than one peak by adjusting the value of span.) (可以通过调整span的值来轻松修改此代码以标记多个峰。)

library(ggplot2)
library(ggpmisc)
library(ggrepel)

ggplot(mtcars, aes(mpg, hp))+
  geom_line()+
  stat_peaks(span = NULL,
             geom = "text_repel",
             mapping = aes(label = paste(..y.label.., ..x.label..)),
             x.label.fmt = "at %.0f mpg",
             y.label.fmt = "Max hp = %.0f",
             segment.colour = "blue",
             arrow = grid::arrow(length = unit(0.1, "inches")),
             nudge_x = 5)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM