如何将曲线拟合到直方图

How to fit a curve to a histogram

我已经探索过关于此主题的类似问题,但在我的直方图上生成漂亮的曲线时遇到了一些问题。我知道有些人可能会认为这是重复的,但我目前还没有找到任何可以帮助解决我的问题的东西。

虽然这里看不到数据,但这里是我使用的一些变量,您可以在下面的代码中看到它们代表什么。

Differences <- subset(Score_Differences, select = Difference, drop = T)
m = mean(Differences)
std = sqrt(var(Differences))

这是我生成的第一条曲线(代码似乎最常见且易于生成,但曲线本身不太适合)。

hist(Differences, density = 15, breaks = 15, probability = TRUE, xlab = "Score Differences", ylim = c(0,.1), main = "Normal Curve for Score Differences")
curve(dnorm(x,m,std),col = "Red", lwd = 2, add = TRUE)

我真的很喜欢这个,但不喜欢曲线进入负区域。

hist(Differences, probability = TRUE)
lines(density(Differences), col = "Red", lwd = 2)
lines(density(Differences, adjust = 2), lwd = 2, col = "Blue")

这是与第一个相同的直方图,但有频率。还是不太好看

h = hist(Differences, density = 15, breaks = 15, xlab = "Score Differences", main = "Normal Curve for Score Differences")
xfit = seq(min(Differences),max(Differences))
yfit = dnorm(xfit,m,std)
yfit = yfit*diff(h$mids[1:2])*length(Differences)
lines(xfit, yfit, col = "Red", lwd = 2)

又一次尝试,但没有成功。可能因为我用的是qnorm,数据明显不正常。曲线再次进入负方向。

sample_x = seq(qnorm(.001, m, std), qnorm(.999, m, std), length.out = l)
binwidth = 3
breaks = seq(floor(min(Differences)), ceiling(max(Differences)), binwidth)
hist(Differences, breaks)
lines(sample_x, l*dnorm(sample_x, m, std)*binwidth, col = "Red")

唯一在视觉上看起来不错的曲线是第2条,但曲线向负方向倾斜。

我的问题是"Is there a "在直方图上放置曲线的标准方法?这个数据肯定不正常。我在这里介绍的 3 个程序来自类似的帖子,但我显然遇到了一些麻烦。我觉得所有拟合曲线的方法都取决于您使用的数据。


更新解决方案

感谢李哲元等人!我会把这个留给自己参考,希望其他人也能参考。

hist(Differences, probability = TRUE)
lines(density(Differences, cut = 0), col = "Red", lwd = 2)
lines(density(Differences, adjust = 2, cut = 0), lwd = 2, col = "Blue")

好的,所以您只是在为 density 超出 "natural range" 的事实而苦苦挣扎。好吧,就设置cut = 0。您可能想阅读 以了解原因。在那个答案中,我使用了 fromto。但是现在我正在使用 cut.

## consider a mixture, that does not follow any parametric distribution family
## note, by construction, this is a strictly positive random variable
set.seed(0)
x <- rbeta(1000, 3, 5) + rexp(1000, 0.5)

## (kernel) density estimation offers a flexible nonparametric approach
d <- density(x, cut = 0)

## you can plot histogram and density on the density scale
hist(x, prob = TRUE, breaks = 50)
lines(d, col = 2)

注意,根据cut = 0,密度估计严格在range(x)内完成。超出此范围,密度为0.