如何在ggplot中的Y中的给定值对应的x值处添加垂直线

时间:2017-02-02 00:52:09

标签: r ggplot2 polynomials

library(polynom)
set.seed(12345)
x<-as.numeric(seq(1,5,0.01))
lp<-rnorm(401,-0.7,1)-4*x+0.9*x^2
link_lp <- exp(lp)/(1 + exp(lp))
y<-ifelse((runif(401) < link_lp),0,1)
df<-data.frame(y=y,x=x)
f<-glm(y~poly(x,degree=2,raw=TRUE),family="binomial")
ymark<-c(0.2,0.3,0.35,0.4,0.45,0.5,0.6)
ggplot(df, aes(x=x, y=y))+
  geom_jitter(size=1, alpha=0.2,height=0.05)+
  stat_smooth(method="glm",
     formula=y~poly(x,degree=2,raw=TRUE),
     method.args =list(family = "binomial"),
     colour="blue", size=1.5)+
  xlab("x")+
  ylab("Probability of event")+theme_bw()+
  geom_hline(yintercept=ymark,col="red")+
  scale_y_continuous(breaks=c(0,ymark,1))

figure 1

接下来我想添加与水平红线对应的垂直线,并添加另一个geom_vline()

ggplot(df, aes(x=x, y=y))+
   geom_jitter(size=1, alpha=0.2,height=0.05)+
   stat_smooth(method="glm",
     formula=y~poly(x,degree=2,raw=TRUE),
     method.args =list(family = "binomial"),
     colour="blue", size=1.5)+
xlab("x")+
ylab("Probability of event")+theme_bw()+
geom_hline(yintercept=ymark,col="red")+
scale_y_continuous(breaks=c(0,ymark,1))+
geom_vline(xintercept=solve(polynomial(coef = coef(f)),
   b=log(ymark/(1-ymark))),col="green")

但是,它报告错误,我该如何更改我的代码?

1 个答案:

答案 0 :(得分:1)

solve返回一个复数。如果你只是想让真实的部分围绕它放置Re

ggplot(df, aes(x=x, y=y))+
  geom_jitter(size=1, alpha=0.2,height=0.05)+
  stat_smooth(method="glm",
              formula=y~poly(x,degree=2,raw=TRUE),
              method.args =list(family = "binomial"),
              colour="blue", size=1.5)+
  xlab("x")+
  ylab("Probability of event")+theme_bw()+
  geom_hline(yintercept=ymark,col="red")+
  scale_y_continuous(breaks=c(0,ymark,1))+
  geom_vline(xintercept=Re(solve(polynomial(coef = coef(f)),
                                         b=log(ymark/(1-ymark)))),col="green")

enter image description here