【问题标题】:How do I get the equation for a regression line in log-log plot in ggplot2?如何在ggplot2的对数图中获得回归线的方程?
【发布时间】:2017-01-04 08:47:15
【问题描述】:

我有一个对数图,我得到了回归线:

geom_smooth(formula = y ~ x, method='lm') 

但现在我想获得这条线的方程式(例如 y=a*x^(-b))并打印出来。我设法在一个 lin-lin 情节中得到它,但在这种情况下不是。 代码如下:

mydataS<-data.frame(DurPeak_h[],IntPeak[],IntPeakxDurPeak[],ID[]) #df peak
names(mydataS)<-c("x","y","ID","IDEVENT")

plotID<-ggplot(mydataS, aes(x=x, y=y, label=IDEVENT)) + 
geom_text(check_overlap = TRUE, hjust = 0, nudge_x = 0.02)+
geom_point(colour="black", size = 2) + geom_point(aes(colour = ID)) +
geom_quantile(quantiles = qs, colour="green")+ 
scale_colour_gradient(low = "white", high="red") +
scale_x_log10(limits = c(min(DurEnd_h),max(DurEnd_h))) + 
scale_y_log10(limits = c(min(IntEnd),max(IntEnd))) +
geom_smooth(formula = y ~ x, method='lm') 

ggsave(height=7,"plot.pdf")

【问题讨论】:

  • 在 ggplot 之外拟合模型可能最简单
  • 你认为方程是从哪里来的?
  • 不要让你的生活变得更加艰难,只要适合lm你自己。 ggplot2 不是建模包。

标签: r ggplot2 equation non-linear-regression


【解决方案1】:
mydataS<-data.frame(DurPeak_h[],IntPeak[],IntPeakxDurPeak[],ID[])
names(mydataS)<-c("x","y","ID","IDEVENT")
model <- lm(y~x, header = T)
summary(model)

使用给出的截距值作为“b”和系数作为你的“a”

【讨论】:

    【解决方案2】:

    做了一个变通办法:使用nls来计算两个参数ab,准确地说:

    nlsPeak <- coef(nls(y ~ a*(x)^b, data = mydataS, start = list(a=30, b=-0.1)))
    

    然后使用annotate 绘制直线(参见一些示例here),最后使用函数打印方程:

    power_eqn = function(ds){
      m = nls(y ~ a*x^b, start = list(a=30, b=-0.1), data = ds);
      eq <- substitute(italic(y) == a  ~italic(x)^b, 
                   list(a = format(coef(m)[1], digits = 4), 
                        b = format(coef(m)[2], digits = 2)))
      as.character(as.expression(eq));
    }
    

    如下调用:

    annotate("text",x = 3, y = 180,label = power_eqn(mydataS), parse=TRUE, col="black") +
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 2017-05-20
      • 1970-01-01
      相关资源
      最近更新 更多