我正在尝试用一个箭头指向线图中的最高点,并在该图上显示一个箭头和最大值来对线图进行注释。我使用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())
提前谢谢你,
发布于 2018-08-06 04:23:50
你是在找这样的东西吗:
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()
添加数据标签。
发布于 2018-08-06 06:25:58
另一种解决方案是使用包'ggpmisc‘和'ggrepel’。(通过调整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)
https://stackoverflow.com/questions/51697870
复制相似问题