【问题标题】:Add a fitting function to histogram向直方图添加拟合函数
【发布时间】:2021-01-14 01:59:05
【问题描述】:
library(ggplot2)
library(fitdistrplus)
set.seed(1)
dat <- data.frame(n = rlnorm(1000))

# binwidth 
bw = 0.2

# fit a lognormal distribution
fit_params <- fitdistr(dat$n,"lognormal")

ggplot(dat, aes(n))  + 
  geom_histogram(aes(y = ..density..), binwidth = bw, colour = "black") + 
  stat_function(fun = dlnorm, size = 1, color = 'gray',
                args = list(mean = fit_params$estimate[1], sd = fit_params$estimate[2]))

# my defined function
myfun <- function(x, a, b) 1/(sqrt(2*pi*b(x-1)))*exp(-0.5*((log(x-a)/b)^2)) # a and b are meanlog and sdlog resp.


我想将myfun 定义的修改对数正态拟合到密度直方图。如何添加此功能?

【问题讨论】:

    标签: r histogram curve-fitting density-plot


    【解决方案1】:

    也许你正在寻找这个。由于您的myfun 的域,某些值无法显示:

    library(ggplot2)
    library(fitdistrplus)
    set.seed(1)
    dat <- data.frame(n = rlnorm(1000))
    
    # binwidth 
    bw = 0.2
    
    # fit a lognormal distribution
    fit_params <- fitdistr(dat$n,"lognormal")
    # my defined function
    myfun <- function(x, a, b) 1/(sqrt(2*pi*b*(x-1)))*exp(-0.5*((log(x-a)/b)^2)) 
    # a and b are meanlog and sdlog resp.
    
    #Plot
    ggplot(dat, aes(n))  + 
      geom_histogram(aes(y = ..density..), binwidth = bw, colour = "black") + 
      stat_function(fun = myfun, size = 1, color = 'gray',
                    args = list(a = fit_params$estimate[1], b = fit_params$estimate[2]))
    

    输出:

    【讨论】:

    • 谢谢。有没有其他方法可以估计拟合参数ab
    • @K.Maya 是的,您可以使用nls() 最小二乘算法或尝试optim() 根据您的函数域设置初始值,以最大化或最小化您的函数!
    猜你喜欢
    • 2019-05-23
    • 2013-11-19
    • 1970-01-01
    • 2018-08-22
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    相关资源
    最近更新 更多