R ggplot-计算多条绘制曲线和几何图形的截距

R ggplot-计算多条绘制曲线和几何图形的截距,r,ggplot2,R,Ggplot2,我想用geom_hline计算像这样的线的插值x截距: 库(dplyr) 图书馆(GG2) g1=数据帧(grp=“1”,x=序列(1,50,1),y=形式(50,5,1)) g2=数据帧(grp=“2”,x=序列(1,30,1),y=形式(30,8,2)) g3=数据帧(grp=“3”,x=序列(1,45,1),y=形式(45,10,1)) 梳状dat=rbind(g1、g2、g3) plot.dat=comb.dat%>%groupby(grp)%>%mutate(cum=cumsum(y

我想用geom_hline计算像这样的线的插值x截距:

库(dplyr)
图书馆(GG2)
g1=数据帧(grp=“1”,x=序列(1,50,1),y=形式(50,5,1))
g2=数据帧(grp=“2”,x=序列(1,30,1),y=形式(30,8,2))
g3=数据帧(grp=“3”,x=序列(1,45,1),y=形式(45,10,1))
梳状dat=rbind(g1、g2、g3)
plot.dat=comb.dat%>%groupby(grp)%>%mutate(cum=cumsum(y)/sum(y))
p1=ggplot(plot.dat,aes(x=x,y=cum,color=grp))+geom_-line()+geom_-hline(yintercept=.5,linetype=“虚线”,color=“黑色”)
打印(p1)
hline=data.frame(plot.dat%%>%groupby(grp)%%>%mutate(test=cum>0.49&cum%groupby(grp)%%>%mutate(F1(0.50))#仅在第一组上有效
g1b=绘图.dat[绘图.dat$grp==“1”,]
F2=近似值(g1b$cum,g1b$x)
F2(0.5)#工作正常但效率低下

我有很多这样的图,我正在寻找最有效的方法来找到x截距,每个因子水平的水平线,这样截距值可以相互比较并注释到图中。我认为有一种逻辑方法,但后来我意识到我需要插值,可能是使用approxfun。我没有找到这是一种不用将组从数据框中分离出来并逐个进行操作的方法……感谢您为我提供了一个直截了当的方法。

这里有一种使用base::appro的dplyr方法

x_seq = seq(1, 50, by = 0.01)
intersections <- plot.dat %>%
  group_by(grp) %>%
  summarise(interpolated = approx(x = x, y = cum, xout = x_seq)$y) %>%
  mutate(x_seq = x_seq) %>%
  slice_min(abs(interpolated - 0.5))

ggplot(plot.dat, aes(x = x, y = cum, color=grp)) +
  geom_line() + 
  geom_hline(yintercept=.5, linetype="dashed", color = "black") +
  geom_point(data = intersections, aes(x_seq, interpolated), size = 3) +
  geom_text(data = intersections, aes(x_seq, interpolated, label = x_seq), vjust = -1)
x_seq=seq(1,50,by=0.01)
交叉点%
分组依据(grp)%>%
总结(内插=大约(x=x,y=cum,xout=x_-seq)$y)%>%
突变(x_-seq=x_-seq)%>%
最小切片(绝对值(插值-0.5))
ggplot(plot.dat,aes(x=x,y=cum,color=grp))+
几何线()
geom_hline(yintercept=.5,linetype=“虚线”,color=“黑色”)+
几何点(数据=交点,aes(x顺序,插值),尺寸=3)+
几何图形文本(数据=交点,aes(x_-seq,插值,标签=x_-seq),vjust=-1)

非常好,谢谢。
x_seq = seq(1, 50, by = 0.01)
intersections <- plot.dat %>%
  group_by(grp) %>%
  summarise(interpolated = approx(x = x, y = cum, xout = x_seq)$y) %>%
  mutate(x_seq = x_seq) %>%
  slice_min(abs(interpolated - 0.5))

ggplot(plot.dat, aes(x = x, y = cum, color=grp)) +
  geom_line() + 
  geom_hline(yintercept=.5, linetype="dashed", color = "black") +
  geom_point(data = intersections, aes(x_seq, interpolated), size = 3) +
  geom_text(data = intersections, aes(x_seq, interpolated, label = x_seq), vjust = -1)