简体   繁体   中英

How do I get the equation for a regression line in log-log plot in ggplot2?

I've a log-log plot, I got the regression line by using:

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

But now I'd like to obtain the equation of this line ( eg y=a*x^(-b)) and print it. I managed to get it in a lin-lin plot but not in this case. Here's the code:

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")
mydataS<-data.frame(DurPeak_h[],IntPeak[],IntPeakxDurPeak[],ID[])
names(mydataS)<-c("x","y","ID","IDEVENT")
model <- lm(y~x, header = T)
summary(model)

use the intercept value given as "b" and the coefficient as your "a"

Did it with a workaround: using nls to calculate the two parameters a and b , precisely:

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

then plotting the line with annotate (see some examples here ) and finally printing the equation using the function:

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));
}

called as follow:

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

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM