Bra*_*don 5 r histogram curve-fitting kernel-density density-plot
我已经探索了有关该主题的类似问题,但是在直方图上生成漂亮曲线时遇到了一些麻烦。我知道有些人可能会认为这是重复的,但我目前还没有找到任何可以帮助解决我的问题的东西。
虽然数据在这里不可见,但这里有一些我正在使用的变量,以便您可以在下面的代码中看到它们代表什么。
Differences <- subset(Score_Differences, select = Difference, drop = T)
m = mean(Differences)
std = sqrt(var(Differences))
Run Code Online (Sandbox Code Playgroud)
这是我生成的第一条曲线(代码似乎最常见且易于生成,但曲线本身不太适合)。
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)
Run Code Online (Sandbox Code Playgroud)
我真的很喜欢这个,但不喜欢曲线进入负区域。
hist(Differences, probability = TRUE)
lines(density(Differences), col = "Red", lwd = 2)
lines(density(Differences, adjust = 2), lwd = 2, col = "Blue")
Run Code Online (Sandbox Code Playgroud)
这是与第一个相同的直方图,但具有频率。看起来还是没那么好看。
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)
Run Code Online (Sandbox Code Playgroud)
又一次尝试,但没有运气。也许是因为我在使用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")
Run Code Online (Sandbox Code Playgroud)
唯一在视觉上看起来不错的曲线是第二条曲线,但曲线落入负方向。
我的问题是“是否有在直方图上放置曲线的“标准方法”?这个数据肯定不正常。我在这里介绍的 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")
Run Code Online (Sandbox Code Playgroud)
density好吧,所以你只是在与超出“自然范围”的事实作斗争。嗯,就设置一下吧cut = 0。您可能想要读取plot.density扩展 \xe2\x80\x9cxlim\xe2\x80\x9d 超出我的数据范围。为什么以及如何解决它?为什么。在那个答案中,我使用了from和to。但现在我正在使用cut.
## consider a mixture, that does not follow any parametric distribution family\n## note, by construction, this is a strictly positive random variable\nset.seed(0)\nx <- rbeta(1000, 3, 5) + rexp(1000, 0.5)\n\n## (kernel) density estimation offers a flexible nonparametric approach\nd <- density(x, cut = 0)\n\n## you can plot histogram and density on the density scale\nhist(x, prob = TRUE, breaks = 50)\nlines(d, col = 2)\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n请注意,通过cut = 0,密度估计严格在 内完成range(x)。在此范围之外,密度为 0。
| 归档时间: |
|
| 查看次数: |
6650 次 |
| 最近记录: |