K. Maya
K. Maya

Reputation: 299

Add a fitting function to histogram

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.


I'd like to fit a modified lognormal defined by myfun to a density histogram. How do I add this function?

Upvotes: 2

Views: 275

Answers (1)

Duck
Duck

Reputation: 39613

Maybe you are looking for this. Some values can not appear because of the domain of your 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]))

Output:

enter image description here

Upvotes: 2

Related Questions