如何在ggplot中拉伸法线?

怪兽猫

我有以下脚本,这会使我的法线曲线太小:

ggplot(exercise2d_df, aes(x=residuals_list)) + 
    geom_histogram(alpha=0.2, position="identity") + 
    stat_function(fun = dnorm, args = c(mean=mean(residuals_list), sd=sd(residuals_list)), size = 1, color = "red")

我的数据是:

residuals_list = c(0.183377698905335, 7.18337769890574, 1.18337769890566, 4.18337769890565, 5.18337769890565, 0.183377698905655, 3.18337769890566,-0.816622301094345, -2.81662230109434, 3.18337769890566, 8.18337769890566, 2.18337769890566, 4.18337769890565, 0.183377698905655, 5.18337769890565, -10.0541259982254, -9.05412599822537, -8.05412599822537, -5.05412599822537, -4.05412599822537, -3.05412599822537, -10.0541259982254, -6.05412599822537, -8.05412599822537, -7.05412599822537, -6.05412599822537, -7.05412599822537, -7.05412599822537, -5.05412599822537, -4.05412599822537, -3.05412599822537, -11.0541259982254, -9.05412599822537, -3.05412599822537, -1.05412599822537, -7.2916296953564, -8.2916296953564, -2.2916296953564, 0.708370304643597, -5.2916296953564, -3.2916296953564, -6.2916296953564, -2.2916296953564, 1.7083703046436, -5.2916296953564, -9.2916296953564, -5.2916296953564, -4.2916296953564, -4.2916296953564, -0.291629695356403, 1.18337769890566, -4.81662230109435, 0.183377698905655, 0.183377698905655, 0.183377698905655, 5.18337769890565, -0.816622301094345, -4.81662230109435, -3.81662230109434, -1.81662230109434, -0.816622301094345, 2.18337769890566, 3.18337769890566, 6.18337769890565, 8.18337769890566, 2.94587400177463, -3.05412599822537, 3.94587400177463, 4.94587400177463, 6.94587400177463, -0.0541259982253741, -0.0541259982253741, -0.0541259982253741, 0.945874001774626, 0.945874001774626, 0.945874001774626, 0.945874001774626, 3.94587400177463, 2.94587400177463, 0.945874001774626, 1.94587400177463, -3.05412599822537, 5.7083703046436, 4.7083703046436, 1.7083703046436, 11.7083703046436, 6.7083703046436, 7.7083703046436, 2.7083703046436, 3.7083703046436, 9.7083703046436, 8.7083703046436, 6.7083703046436, 6.7083703046436, -0.291629695356403, 5.7083703046436, 4.7083703046436, -1.2916296953564, 9.7083703046436, 8.7083703046436, 1.7083703046436, 2.7083703046436, 3.7083703046436)

此代码创建如下图:

结果图

如何拉伸法线以使其适合直方图?

(请注意,这不是关于如何将普通曲线叠加到ggplot中的直方图上的问题,即使那是我最终追求的目标,因此这不是重复的。)

格雷格·斯诺(Greg Snow)

法线曲线下的当前面积为1,直方图的面积为条形的宽度乘以点数。因此,如果将法线曲线的高度乘以该值,则它将具有相同的面积。以下工作(使用默认的binwidth计算,可能更好/更直接地指定binwidth):

tmpfun <- function(x,mean,sd) {
    diff(range(residuals_list))/30*length(residuals_list)*dnorm(x,mean,sd)
}


ggplot(exercise2d_df, aes(x=residuals_list)) + 
    geom_histogram(alpha=0.2, position="identity") + 
    stat_function(fun = tmpfun, args = c(mean=mean(residuals_list), 
        sd=sd(residuals_list)), size = 1, color = "red")

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章