繁体   English   中英

直方图中的Matlab图

[英]Matlab plot in histogram

假设y是一个遵循分布f(x)=sqrt(4-x^2)/(2*pi)具有随机数的向量。 目前,我使用命令hist(y,30) 如何将分布函数f(x)=sqrt(4-x^2)/(2*pi)绘制到同一直方图中?

让我们以另一个分布函数(标准正态)为例。 要完全按照您的意愿进行操作,请执行以下操作:

nRand = 10000;
y = randn(1,nRand);
[myHist, bins] = hist(y,30);
pdf = normpdf(bins);
figure, bar(bins, myHist,1); hold on; plot(bins,pdf,'rx-'); hold off;

这可能不是您真正想要的。 为什么? 您会注意到,密度函数在直方图底部看起来像一条细线。 这是因为直方图是对二进制数进行计数,而密度函数被归一化为一个整数。 如果箱中有数百个项目,则密度函数将无法与比例尺相匹配,因此会出现缩放或归一化问题。 您必须对直方图进行归一化,或者绘制比例分布函数。 我更喜欢对分布函数进行缩放,以便在查看直方图时,我的计数是有意义的:

normalizedpdf = pdf/sum(pdf)*sum(myHist);
figure, bar(bins, myHist,1); hold on; plot(bins,normalizedpdf,'rx-'); hold off;

您的情况是一样的,除了将使用指定的函数f(x)代替normpdf命令。

除了对数值进行归一化,您还可以通过以下方法找到理论比例因子来实现。

nbins = 30;
nsamples = max(size(y));
binsize = (max(y)-min(y)) / nsamples
hist(y,nbins)
hold on
x1=linspace(min(y),max(y),100);
scalefactor = nsamples * binsize 
y1=scalefactor * sqrt(4-x^2)/(2*pi)
plot(x1,y1)

更新: 工作原理。

对于任何足够大以能够很好地近似pdf的数据集(称为f(x)),在该域上f(x)的积分将近似为1。 但是,我们知道任何直方图下的面积正好等于样本总数乘以bin宽度。

因此,使pdf与直方图一致的一个非常简单的比例因子是Ns * Wb,即采样点总数乘以分格宽度。

让我添加另一个示例:

%# some normally distributed random data
data = randn(1e3,1);

%# histogram
numbins = 30;
hist(data, numbins);
h(1) = get(gca,'Children');
set(h(1), 'FaceColor',[.8 .8 1])

%# figure out how to scale the pdf (with area = 1), to the area of the histogram
[bincounts,binpos] = hist(data, numbins);
binwidth = binpos(2) - binpos(1);
histarea = binwidth*sum(bincounts);

%# fit a gaussian
[muhat,sigmahat] = normfit(data);
x = linspace(binpos(1),binpos(end),100);
y = normpdf(x, muhat, sigmahat);
h(2) = line(x, y*histarea, 'Color','b', 'LineWidth',2);

%# kernel estimator
[f,x,u] = ksdensity( data );
h(3) = line(x, f*histarea, 'Color','r', 'LineWidth',2);

legend(h, {'freq hist','fitted Gaussian','kernel estimator'})

历史

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM