我正在寻找最优雅的方法来将正态分布拟合叠加到分组直方图中ggplot2
。我知道这个问题之前已经被问过很多次了,但是没有一个建议的选项,比如this one https://stackoverflow.com/questions/7182556/how-to-add-gaussian-curve-to-histogram-created-with-qplot or this one https://stackoverflow.com/questions/1376967/using-stat-function-and-facet-wrap-together-in-ggplot2-in-r我觉得非常优雅,至少不是,除非stat_function
可以对数据的每个特定部分进行处理。
我遇到的一种将正态分布拟合叠加到非分组直方图上的相对优雅的方法是使用geom_smooth
and method="nls"
(除了它不是自启动函数并且必须指定起始值这一事实之外):
library(ggplot2)
myhist = data.frame(size = 10:27, counts = c(1L, 3L, 5L, 6L, 9L, 14L, 13L, 23L, 31L, 40L, 42L, 22L, 14L, 7L, 4L, 2L, 2L, 1L) )
ggplot(data=myhist, aes(x=size, y=counts)) + geom_point() +
geom_smooth(method="nls", formula = y ~ N * dnorm(x, m, s), se=F,
start=list(m=20, s=5, N=300))
我想知道这种方法是否也可以用于将正态分布拟合添加到分组直方图,如
library(devtools)
install_github("tomwenseleers/easyGgplot2",type="source")
library("easyGgplot2") # load weight data
ggplot(weight,aes(x = weight)) +
+ geom_histogram(aes(y = ..count.., colour=sex, fill=sex),alpha=0.5,position="identity")
我还想知道是否有任何包可以定义+ stat_distrfit()
or + stat_normfit(
) for ggplot2
有没有机会(有分组的可能性)? (我真的找不到任何东西,但这似乎是一个很常见的任务,所以我只是想知道)
我希望代码尽可能短的原因是这是一个课程,并且我想让事情尽可能简单......
PS geom_density
不适合我的目标,我还想绘制计数/频率而不是密度。我还想将它们放在同一个面板中,并避免使用facet_wrap