我已经探索了有关该主题的类似问题,但是在直方图上生成漂亮曲线时遇到了一些麻烦。我知道有些人可能会认为这是重复的,但我目前还没有找到任何可以帮助解决我的问题的东西。
虽然数据在这里不可见,但这里有一些我正在使用的变量,以便您可以在下面的代码中看到它们代表什么。
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")
唯一在视觉上看起来不错的曲线是第二条曲线,但曲线落入负方向。
我的问题是 “是否有在直方图上放置曲线的“标准方法”? 这个数据肯定不正常。我在这里介绍的 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
而苦苦挣扎。超出“自然范围”。好吧,只需设置cut = 0
.您可能想阅读 plot.density
extends “xlim” beyond the range of my data. Why and how to fix it?为什么。在那个答案中,我使用的是 from
和 to
.但现在我正在使用 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。
关于r - 如何将曲线拟合到直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41291116/