Multiple stat_function on grouped data with ggplot2

前端 未结 2 1195
余生分开走
余生分开走 2021-01-14 09:35

I am studying a data set with multiple observation of a parameter overtime. the data is like:

test<-data.frame(t = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.33, 0         


        
相关标签:
2条回答
  • 2021-01-14 10:32

    I thought of another naive solution: Predicting the values of every dlnorm().

    ## Split up the data according to t
    tt     <- split(test, test$t)
    
    ## Fit a lognormal to every dataset
    fits   <- lapply(tt, function(x) fitdistr(x$int, "lognormal"))
    
    ## Predict values
    fitted <- lapply(fits, function(x) dlnorm(x = 1:max(test$int),
                                   mean = x$estimate[1], sd = x$estimate[2]))
    
    ## Wrap everything into a data.frame ggplot can handle
    plot.data <- data.frame(y = unlist(fitted), int = 1:max(test$int),
                            t = rep(unique(test$t),
                                each = length(unlist(fitted))/length(unique(test$t))))
    
    ## Plot
    ggplot(test, aes(int, group = as.factor(t), colour=t)) +
      #geom_density() +
      geom_line(data = plot.data, aes(y = y), lwd = 1)
    
    0 讨论(0)
  • 2021-01-14 10:33

    What about a naive solution, adding iteratively stat_function()?

        cols <- brewer.pal(length(unique(test$t)),"Set1")
        g <- ggplot(data=subset(test, t == 0, select='int'), aes(x=int))
        n <- 1
        for(i in unique(test$t)){ 
            fit <- fitdistr(subset(test, t == i, select='int')$int, "lognormal")
            g <- g+stat_function(fun = dlnorm, 
                                 args=list(mean=fit$estimate[1],sd=fit$estimate[2]), 
                                 col=cols[n])
            n <- n + 1
        }
        g
    
    0 讨论(0)
提交回复
热议问题