是否可以在 gnuplot 中绘制正态概率分布

Whether is it possible to plot normal probability distribution in gnuplot

我的数据文件是-

 2 3 4 1 5 2 0 3 4 5 3 2 0 3 4 0 5 4 3 2 3 4 4 0 5 3 2 3 4 5 1 3 4

我的要求是在 gnuplot 中绘制普通 PDF。 我可以通过计算 f(x)

f(x) = \frac{1}{\sqrt{2\pi\sigma^2} } e^{ -\frac{(x-\mu)^2}{2\sigma^2} } 
for each x using shell script. 

然后我使用命令-

在 gnuplot 中绘制它
plot 'ifile.txt' using 1:2 with lines

但是是否可以直接在 gnuplot 中绘图?

gnuplot 在 smooth 关键字下提供了许多处理选项(尝试输入 help smooth 以获得更多信息)。不过,对于您的具体情况,我会推荐合适的。

首先,请注意您的数据点是连续的,您需要将其转换为列以供 gnuplot 使用。你可以用 awk:

awk '{for (i=1;i<=NF;i++) print $i}' datafile

可以从 gnuplot 中调用:

plot "< awk '{for (i=1;i<=NF;i++) print $i}' datafile" ...

为简单起见,现在假设 datafile 具有正确的格式。

您可以使用 smooth frequency 选项查看每个值出现的次数:

plot "datafile" u 1:(1.) smooth frequency w lp pt 7

要获得归一化分布,请除以值的数量。这可以在 gnuplot 中使用 stats:

自动完成
stats "datafile"

这会将值的数量存储在变量 STATS_records 中,在您的例子中,它的值为 33:

gnuplot> print STATS_records
33.0

所以归一化分布(在 x 处得到一个值的概率)是:

plot "datafile" u 1:(1./STATS_records) smooth frequency w lp pt 7

如您所见,您的分布看起来并不像正态分布,但无论如何,让我们继续。创建一个用于拟合和拟合数据的高斯分布,并绘制它。您需要适应概率,而不是数据本身。为此,我们绘制到 table 以提取由 smooth frequency:

生成的数据
# Non-normalized Gaussian
f(x)= A * exp(-(x-x0)**2/2./sigma**2)
# Save probability data to table
set table "probability"
plot "datafile" u 1:(1./STATS_records) smooth frequency not
unset table
# Fit the Gaussian to the data, exclude points from table with grep
fit f(x) "< grep -v 'u' probability" via x0, sigma, A
# Normalize the gaussian
g(x) = 1./sqrt(2.*pi*sigma**2) * f(x) / A
# Plot
plot "datafile" u 1:(1./STATS_records) smooth frequency w lp pt 7, g(x)

set table 生成一些你应该排除的点,这就是为什么我使用 grep 来过滤文件。此外,在以可变幅度完成拟合后,需要对高斯进行归一化。如果要检索拟合参数:

gnuplot> print x0, sigma
3.40584703189268 1.76237558717934

最后请注意,如果数据点之间的间距不均匀,例如而不是 x = 0, 1, 2, 3 ... 你的值在 x = 0, 0.1, 0.5, 3, 3.2 ... 然后你需要使用不同的方式来做到这一点,例如定义常规大小的容器来分组数据点。