我会这样做,使用以下命令从 R 生成 n=500 个随机高斯变量:
Rscript -e 'cat(rnorm(500), sep="\\n")' > rnd.dat
我使用与您完全相同的想法来定义标准化直方图,其中 y 定义为 1/(binwidth * n),除了我使用 int 而不是 floor 并且我没有在仓值。简而言之,这是对smooth.dem 演示脚本的快速改编,Janert 的教科书中描述了类似的方法,Gnuplot in Action(Chapter 13,第 257 页,免费提供)。您可以将我的示例数据文件替换为 random-points,它位于 Gnuplot 附带的 demo 文件夹中。请注意,我们需要将点数指定为 Gnuplot,因为文件中的记录没有计数功能。
bw1=0.1
bw2=0.3
n=500
bin(x,width)=width*int(x/width)
set xrange [-3:3]
set yrange [0:1]
tstr(n)=sprintf("Binwidth = %1.1f\n", n)
set multiplot layout 1,2
set boxwidth bw1
plot 'rnd.dat' using (bin($1,bw1)):(1./(bw1*n)) smooth frequency with boxes t tstr(bw1)
set boxwidth bw2
plot 'rnd.dat' using (bin($1,bw2)):(1./(bw2*n)) smooth frequency with boxes t tstr(bw2)
这是结果,有两个 bin 宽度
此外,这确实是一种粗略的直方图方法,在 R 中很容易获得更详细的解决方案。事实上,问题是如何定义一个好的 bin 宽度,这个问题已经在 stats.stackexchange.com 上讨论过:使用 @ 987654325@ 分箱规则实施起来应该不会太难,但您需要计算四分位间距。
这是 R 将如何处理相同的数据集,使用默认选项(Sturges 规则,因为在这种特殊情况下,这不会产生影响)和上面使用的等间距 bin。
使用的R代码如下:
par(mfrow=c(1,2), las=1)
hist(rnd, main="Sturges", xlab="", ylab="", prob=TRUE)
hist(rnd, breaks=seq(-3.5,3.5,by=.1), main="Binwidth = 0.1",
xlab="", ylab="", prob=TRUE)
您甚至可以通过检查调用 hist() 时返回的值来了解 R 是如何工作的:
> str(hist(rnd, plot=FALSE))
List of 7
$ breaks : num [1:14] -3.5 -3 -2.5 -2 -1.5 -1 -0.5 0 0.5 1 ...
$ counts : int [1:13] 1 1 12 20 49 79 108 87 71 43 ...
$ intensities: num [1:13] 0.004 0.004 0.048 0.08 0.196 0.316 0.432 0.348 0.284 0.172 ...
$ density : num [1:13] 0.004 0.004 0.048 0.08 0.196 0.316 0.432 0.348 0.284 0.172 ...
$ mids : num [1:13] -3.25 -2.75 -2.25 -1.75 -1.25 -0.75 -0.25 0.25 0.75 1.25 ...
$ xname : chr "rnd"
$ equidist : logi TRUE
- attr(*, "class")= chr "histogram"
这就是说,如果您愿意,您可以使用 R 结果通过 Gnuplot 处理您的数据(尽管我建议直接使用 R :-)。