首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何用箭头和最大值标注线条图?

如何用箭头和最大值标注线条图?
EN

Stack Overflow用户
提问于 2018-08-06 04:08:29
回答 2查看 3.5K关注 0票数 5

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

代码语言:javascript
复制
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())

提前谢谢你,

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-06 04:23:50

你是在找这样的东西吗:

代码语言:javascript
复制
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")

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

票数 8
EN

Stack Overflow用户

发布于 2018-08-06 06:25:58

另一种解决方案是使用包'ggpmisc‘和'ggrepel’。(通过调整span的值,可以很容易地修改此代码以标记多个峰值。)

代码语言:javascript
复制
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)

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51697870

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档