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

标签 r ggplot2 annotations ggpmisc

我正在尝试用指向线图中最高点的箭头注释线图,并在图上显示箭头和最大值。我正在使用 mtcars数据集作为我的引用。下面是我的代码。

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

提前致谢,

最佳答案

您是否正在寻找这样的东西:

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

解释:为了标注最大值,我们需要找到 mpg 的位置,即 hp 的最大值。为此,我们使用 mtcars[which(mtcars$hp == max(mtcars$hp)), "mpg"] . which()语句为我们提供了该最大值的行位置,以便我们可以获得正确的 mpg 值。接下来我们用这个位置注释添加一点空间(即+2和+.2),使它看起来更好。最后,我们可以构造一个位置相同(但偏移量不同)的数据框,并使用 geom_text()添加数据标签。

关于r - 如何用箭头和最大值注释线图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51697870/

相关文章:

r - 根据变量重要性对输出进行排序(插入符号包)

r - 打印没有行和列索引的矩阵

java - Lombok 注释中的编译错误-Eclipse

java - ArchUnit - 确保方法参数被注释

javascript - Google Charts 注释时间线提示未出现

r - R中的向量化顺序

r - 了解 RStudio 的工作区选项卡 lm 表示法

r - 在 for 循环中使用 ggplot2 的多个图

r - ggplot轴标题中斜体和上标的表达

r - geom_point 在 geom_极地饼图(圆环图)图表的开头引入偏移