向直方图添加拟合函数

问题描述

SQLEXPRESS01

我想将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的域,某些值无法显示:

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]))

输出:

enter image description here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...