Search code examples
rggplot2interpolationsmoothing

using a custom function for smoothing


I recently started learning R and ran into a problem using a custom function when plotting. I want to use the rosin-rammler equation but can't figure out how to use it in my case. In Mathkad, this was easily solved. And here I can not understand.

This is an example of my data and code.

xy yy cat1 sem1
0 0 0 №1
10 3 0 №1
20 30 0 №1
30 18 0 №1
40 15 0 №1
50 13 0 №1
60 8 0 №1
70 5 0 №1
80 3 0 №1
90 2 0 №1
100 0 0 №1
110 0 0 №1
ggplot(allOnw, aes(x = xy, y=yy, col = sem1)) +geom_point()+
  guides(fill = FALSE) +  labs(col="S" )+theme(legend.position="bottom")  +scale_x_continuous(breaks = seq(from = 0, to = 160, by = 10), limits = c(0,160))+
  scale_color_manual(values = c("blue", "cyan", "darkgreen","darkorange","gold","darkorchid")) + 
  facet_wrap(vars(cat1),ncol = 1, strip.position = "right")+labs(x ="MP")+labs(y = "GT ")

I would like the graph to end up looking like when using geom_density. What can i do for this? Is it possible?


Solution

  • If you have a particular model to fit to your points, you can use method = nls inside geom_smooth.

    As far as I can tell from the literature, the function you are trying to fit takes this form:

    rosin_rammler <- function(x, A, B, C) {
      C * ((A / x) * (x / B)^A * exp(-((x / B)^(A - 1))))
    }
    

    And we can use this directly inside geom_smooth:

    ggplot(allOnw, aes(x = xy + 1e-6, y = yy, col = sem1)) +
      geom_point() +
      geom_smooth(formula = y ~ rosin_rammler(x, A, B, C), method = nls,
                  method.args = list(algorithm = "port",
                                     start = list(A = 5, B = 20, C = 1000), 
                                     lower = c(1, 1)), se = FALSE, n = 1000) +
      labs(col = "S", x = "MP", y = "GT")+
      theme(legend.position = "bottom")  +
      scale_x_continuous(breaks = 0:16 * 10, limits = c(0, 160)) +
      scale_color_manual(values = c("blue", "cyan", "darkgreen", 
                                          "darkorange", "gold", "darkorchid")) + 
      facet_wrap(vars(cat1), ncol = 1, strip.position = "right") 
    

    enter image description here