【问题标题】:How to plot multiple logistic regression curves on one plot in Ggplot 2如何在 Ggplot 2 的一个图上绘制多条逻辑回归曲线
【发布时间】:2015-01-12 19:51:05
【问题描述】:

我的数据框示例如下:

ent corp smb  fit  se.fit   UL    LL  PredictedProb 
  1   0   0  -2.54   0.10  0.087 0.06         0.072   
  0   0   1  -3.71   0.05  0.026 0.02         0.023 
  0   1   0  -3.60   0.05  0.029 0.02         0.026      
  1   0   0  -2.54   0.10  0.087 0.060        0.072      
  0   0   1  -3.71   0.05  0.026 0.021        0.023      

我想制作 3 个图,根据预测概率为每个二进制 (sent,corp,smb) 绘制一条最佳拟合线 - 如果可能的话,我还想为预测概率添加点。到目前为止,我已经能够创建 3 个单独的地块,但我想将所有三个地块放在一个地块上。以下是我目前所拥有的:

这是 Corp 情节的代码:

corp.line <- ggplot(newdata3, aes(corp,PredictedProb)) corp.line <- corp.line + stat_smooth(method = "glm") corp.line

这是 SMB 图的代码:

smb.line <- ggplot(newdata3, aes(smb,PredictedProb)) smb.line <- smb.line + stat_smooth(method = "glm") smb.line

这是 Ent 图的代码:

ent.line <- ggplot(newdata3, aes(enterprise,PredictedProb)) ent.line <- ent.line + stat_smooth(method="glm",family= binomial(link="logit")) ent.line

另外,在上一个图中,我无法使用 stat_smooth(method = "glm") 围绕最佳拟合线绘制平滑曲线。我还必须添加 family = binomial(link="logit")。有谁知道为什么会这样。

重申一下,我的主要问题是如何将所有这三个都绘制在一个情节上,而不必将它们分开。另外,我想为预测概率加分。

请代表我原谅任何不当行为。我对堆栈交换和 ggplot2 还是很陌生。

【问题讨论】:

标签: r ggplot2 regression logistic-regression


【解决方案1】:

您将无法绘制通过逻辑回归获得的“S”形曲线,因为您没有要绘制的连续变量。相反,您只能在这些预测值周围绘制预测值和 CI。

在您的数据框中创建一个包含 ent、corp 和 smb 的列。

newdata3<-read.table("clipboard", header=T)
newdata4<-unique(newdata3)[-4,] #different lower limits for smb... removing the second smb LL


newdata4$NewVar<-rep("",length(newdata[,1]))
newdata4$NewVar[which(newdata3$ent==1)]<-"ent"
newdata4$NewVar[which(newdata3$corp==1)]<-"corp"
newdata4$NewVar[which(newdata3$smb==1)]<-"smb"

windows(5,5)
ggplot(newdata4, aes(NewVar, PredictedProb, colour=NewVar)) + geom_point() +
    geom_errorbar(aes(ymin=LL, ymax=UL), width=.1, size=1)

【讨论】:

  • 嘿,感谢您的帮助。在我考虑了更多之后,我得出了关于没有连续预测器的相同结论。另外,如果你有时间,你能解释一下 which 和 unique 命令在做什么吗?再次感谢!
  • unique(),应用于整个数据框,删除任何重复的行。如果您不这样做,您将一遍又一遍地绘制相同的东西,这可能会或可能不会成为您的图表最终外观的问题。运行 unique(newdata3) 命令并查看 R 返回什么。使用 which() 函数,我查看了您的每一列(ent、corp 和 smb),发现哪些行等于 1,然后我将该列名称分配给我的 NewVar 中的特定行。我解开了你的指标变量。运行 which(newdata3$ent==1) 以查看返回的内容。查看每个函数上的help()
猜你喜欢
  • 1970-01-01
  • 2016-08-09
  • 2014-03-16
  • 1970-01-01
  • 1970-01-01
  • 2015-02-19
  • 2017-11-05
  • 2018-10-13
  • 2019-10-20
相关资源
最近更新 更多