r - 如何将曲线拟合到直方图

标签 r histogram curve-fitting kernel-density density-plot

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

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

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)

enter image description here

我真的很喜欢这个,但不喜欢曲线进入负区域。
hist(Differences, probability = TRUE)
lines(density(Differences), col = "Red", lwd = 2)
lines(density(Differences, adjust = 2), lwd = 2, col = "Blue")

enter image description here

这是与第一个相同的直方图,但具有频率。看起来还是没那么好看。
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)

enter image description here

又一次尝试,但没有运气。也许是因为我正在使用 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")

enter image description here

唯一在视觉上看起来不错的曲线是第二条曲线,但曲线落入负方向。

我的问题是 “是否有在直方图上放置曲线的“标准方法”? 这个数据肯定不正常。我在这里介绍的 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")

enter image description here

最佳答案

好的,所以您只是在为 density 而苦苦挣扎。超出“自然范围”。好吧,只需设置cut = 0 .您可能想阅读 plot.density extends “xlim” beyond the range of my data. Why and how to fix it?为什么。在那个答案中,我使用的是 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)

enter image description here

注意,作者 cut = 0 , 密度估计严格在 range(x) 内完成.在此范围之外,密度为 0。

关于r - 如何将曲线拟合到直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41291116/

相关文章:

3D 中的 MATLAB 曲线拟合,具有附加边界

r - R中的自引用嵌套函数?

image - 如何在 Matlab 中显示 RGB 图像的直方图?

python - matplotlib.pyplot.plotfile() - 如何将多个图形绘制到同一个图形中?

python - 绘制直方图箱的箱线图以进行直方图比较

curve-fitting - 给定三个点如何计算抛物线的顶点

matlab - 从样条拟合中获取 y 值

r - 绘制和保存 R 图

r - 在 browser() 中使用 <<- (全局赋值)将列表附加到列表

r - 如何在R中编辑多人对象