簡體   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