# A mixture of normal distributions where the standard deviation is
# inverse gamma distributed resembles a cauchy distribution.
x <- rnorm(2000, 10, 1/rgamma(2000, 2, 0.5))
df <- data.frame(x = x)
ggplot(df, aes(x)) +
geom_histogram(binwidth = 0.1,
alpha = 0.3, position = "identity") +
stat_theodensity(aes(y = stat(count) * 0.1, colour = "Normal"),
distri = "norm", geom = "line") +
stat_theodensity(aes(y = stat(count) * 0.1, colour = "Cauchy"),
distri = "cauchy", geom = "line") +
coord_cartesian(xlim = c(5, 15))
# A negative binomial can be understood as a Poisson-gamma mixture
df <- data.frame(x = c(rpois(500, 25),
rpois(500, rgamma(500, 5, 0.2))),
cat = rep(c("Poisson", "Poisson-gamma"), each = 500))
ggplot(df, aes(x)) +
geom_histogram(binwidth = 1, aes(fill = cat),
alpha = 0.3, position = "identity") +
stat_theodensity(aes(y = stat(count), colour = cat), distri = "nbinom",
geom = "step", position = position_nudge(x = -0.5)) +
stat_summary(aes(y = x, colour = cat, x = 1),
fun.data = function(x){data.frame(xintercept = mean(x))},
geom = "vline")
Run the code above in your browser using DataLab