【发布时间】:2026-01-14 17:35:01
【问题描述】:
我正在寻找在ggplot2 的分组直方图中叠加正态分布拟合的最优雅方法。我知道这个问题之前已经被问过很多次了,但是没有一个建议的选项,比如this one 或this one 让我觉得非常优雅,至少除非stat_function 可以在每个特定小节上工作数据。
将正态分布拟合叠加到我确实遇到的非分组直方图上的一种相对优雅的方法是使用 geom_smooth 和 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")
我还想知道是否有任何可能为ggplot2 定义+ stat_distrfit() 或+ stat_normfit() 的包(有可能进行分组)? (我真的找不到任何东西,但这似乎是一个足够常见的任务,所以我只是想知道)
我希望代码尽可能短的原因是这是为了一门课程,我想让事情尽可能简单......
PS geom_density 不适合我的目标,我还想绘制计数/频率而不是密度。我也想让它们在同一个面板中,避免使用facet_wrap
【问题讨论】:
-
看看this post。
标签: r ggplot2 histogram normal-distribution