我正在尝试用指向线图中最高点的箭头注释线图,并在图上显示箭头和最大值。我正在使用 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")
解释:为了标注最大值,我们需要找到 mpg 的位置,即 hp 的最大值。为此,我们使用
mtcars[which(mtcars$hp == max(mtcars$hp)), "mpg"]
. which()
语句为我们提供了该最大值的行位置,以便我们可以获得正确的 mpg 值。接下来我们用这个位置注释添加一点空间(即+2和+.2),使它看起来更好。最后,我们可以构造一个位置相同(但偏移量不同)的数据框,并使用 geom_text()
添加数据标签。
关于r - 如何用箭头和最大值注释线图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51697870/