使用ggplot的非线性模型绘图问题

时间:2021-06-29 08:29:57

标签: r ggplot2 smoothing nls

我在通过 stat_smooth 绘制 NLS 拟合时遇到问题。有趣的是,拟合曲线在负 y 方向移动。有谁知道这可能是什么原因?下面是代码、数据和示例图(URL):

y<-c(0.686, 0.674, 0.631, 0.580, 0.520, 0.440, 0.411, 0.401, 0.338, 0.262, 0.218, 0.703, 0.628,0.584, 0.547, 0.513, 0.457, 0.395, 0.372, 0.326, 0.255, 0.213, 0.760, 0.684, 0.622, 0.577, 0.550, 0.463, 0.395, 0.352, 0.311, 0.244, 0.212)
x<-c(0.03,  0.08,  0.15,  0.23,  0.30,  0.75,  1.50,  2.25,  3.01,  7.52, 15.03,  0.03,  0.08, 0.15,  0.23,  0.30,  0.75,  1.50,  2.25,  3.01,  7.52, 15.03,  0.03,  0.08,  0.15,  0.23,0.30,  0.75,  1.50,  2.25,  3.01,  7.52, 15.03)  
df<-as.data.frame(cbind(x,y)) 
ggplot(df,aes(x=x,y=y))+
  geom_point()+
  stat_smooth(method = "nls", formula = log10(y) ~ c1*log10(x)+c2,
              method.args=list(start=list(c1=-0.2,c2=-0.4)),
              se=FALSE)

enter image description here

非常感谢 XEZ

1 个答案:

答案 0 :(得分:1)

就像评论中提到的 stefan 一样,那是因为你适合 log10(y)。转换输入值的另一种解决方案是在计算拟合后反转对数转换。您可以使用 stage() 函数执行此操作:

library(ggplot2)

y<-c(0.686, 0.674, 0.631, 0.580, 0.520, 0.440, 0.411, 0.401, 0.338, 0.262, 0.218, 0.703, 0.628,0.584, 0.547, 0.513, 0.457, 0.395, 0.372, 0.326, 0.255, 0.213, 0.760, 0.684, 0.622, 0.577, 0.550, 0.463, 0.395, 0.352, 0.311, 0.244, 0.212)
x<-c(0.03,  0.08,  0.15,  0.23,  0.30,  0.75,  1.50,  2.25,  3.01,  7.52, 15.03,  0.03,  0.08, 0.15,  0.23,  0.30,  0.75,  1.50,  2.25,  3.01,  7.52, 15.03,  0.03,  0.08,  0.15,  0.23,0.30,  0.75,  1.50,  2.25,  3.01,  7.52, 15.03)  
df<-as.data.frame(cbind(x,y)) 
ggplot(df,aes(x=x,y=y))+
  geom_point()+
  stat_smooth(method = "nls", formula = log10(y) ~ c1*log10(x)+c2,
              method.args=list(start=list(c1=-0.2,c2=-0.4)),
              aes(y = stage(y, after_stat = 10^y)),
              se=FALSE)

reprex package (v1.0.0) 于 2021 年 6 月 29 日创建