R 向直方图添加拟合函数 库(ggplot2) 图书馆(FitPlus) 种子(1) dat
也许你在找这个。由于您的R 向直方图添加拟合函数 库(ggplot2) 图书馆(FitPlus) 种子(1) dat,r,histogram,curve-fitting,density-plot,R,Histogram,Curve Fitting,Density Plot,也许你在找这个。由于您的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") ggplot(dat, aes(n))
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")
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.
库(ggplot2)
图书馆(FitPlus)
种子(1)
谢谢。是否有其他方法来估计拟合参数a
和b
@K.Maya是的,您可以使用nls()
这是一种最小二乘算法,或者尝试optim()
根据函数的域设置初始值,以最大化或最小化函数!
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]))