Search code examples
rggplot2curve-fitting

apparently correct rscript does not plot curve in ggplot 2


I have tried different script options from other related questions but none seems to plot the desired curve, despite the script looks correct and runs... https://www.dropbox.com/s/efxbx6qh4z32snx/examplecurve.csv?dl=0

d=read.csv("examplecurve.csv")
require(nlme)
model <- nls(y ~ a*(x^b),start = list(a = exp(coef(m)[1]), b = 
coef(m)[2]),  data = d)
summary(model)
fontsize=12
ggplot(d, aes(x=x, y=y)) +
geom_point(col="black", fill = "grey",alpha=0.8, shape=21, size = 2) +
stat_smooth(method = "nls", 
        method.args = list(formula = y ~ a*(x^b),
    method.args = list(formula = y ~ a*(x^b), 
    start = list(coef(model))),
    se = F, size = 0.5, data = d))+
                        
   theme(panel.background = element_rect(fill='transparent', 
 colour='black'),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    axis.title.x = element_text(colour="black", size=fontsize),
    axis.text.x  = element_text(angle=0, vjust=0.5,colour="black", 
 size=fontsize),
    axis.title.y = element_text(colour="black", size=fontsize),
    axis.text.y  = element_text(angle=0, vjust=0.5,colour="black", 
 size=fontsize)
 )+  theme(legend.position="none",
        legend.justification=c(1,1),
        legend.key = element_rect(fill = 'transparent'),
        legend.background = element_rect(fill = 'transparent'),
        legend.text = element_text(size = 12))

I would also like to add error ribbons...

T hanks in advance!


Solution

  • Borrowing from this previous answer of mine, you can add an error ribbon around an nls fit using these little functions:

    nls_se <- function(formula, data, start, ...) {
      mod <- nls(formula, data, start)
      class(mod) <- "nls_se"
      mod
    }
    
    predict.nls_se <- function(model, newdata, level = 0.9, ...) {
      class(model) <- "nls"
      p <- investr::predFit(model, newdata = newdata, 
                            interval = "confidence", level = level)
      list(fit = p, se.fit = p[,3] - p[,1])
    }
    

    These allow you to use geom_smooth directly with your target formula:

    ggplot(d, aes(x = x, y = y)) +
      geom_point(col="black", fill = "grey",alpha = 0.8, shape = 21, size = 2) +
      geom_smooth(method = nls_se, formula = y ~ a * x^b,
                  method.args = list(start = list(a = 1, b = 1))) 
    

    enter image description here

    Or, with some styling choices (thanks Rui Barradas)

    ggplot(d, aes(x = x, y = y)) +
      geom_point(col="black", fill = "grey",alpha = 0.8, shape = 21, size = 2) +
      geom_smooth(method = nls_se, formula = y ~ a * x^b,
                  method.args = list(start = list(a = 1, b = 1)),
                  color = "navy", fill = "deepskyblue4", alpha = 0.2,
                  linetype = 2, linewidth = 0.4) +
      theme_Agus_camacho(20)
    

    enter image description here