Matlab中直方图的绘制

histogram函数

直方图属于数值数据的条形图类型,将数据分组为 bin。创建 Histogram 对象后,可以通过更改直方图的属性值修改它的各个方面。

histogram(X)

histogram(X,nbins)

histogram(X,edges)

histogram('BinEdges',edges,'BinCounts',counts)

histogram(C)

histogram(C,Categories)

histogram('Categories',Categories,'BinCounts',counts)

histogram(___,Name,Value)

histogram(ax,___)

h = histogram(___)

注释:

X-要分布到各bin的数据

C-分类数据

nbins-bin数量

edges-bin边界

Categories-直方图中包含的类别

counts-bin计数

ax-目标坐标区

1.向量直方图

生成 10,000 个随机数并创建直方图。histogram 函数自动选择合适的 bin 数量,以便涵盖 x 中的值范围并显示基本分布的形状。

x = randn(10000,1);

h = histogram(x)

2.指定直方图的bin数量

对分类为 25 个等距 bin 的 1,000 个随机数绘制直方图。

x = randn(1000,1);

nbins = 25;

h = histogram(x,nbins)

3.更改直方图的bin数量

生成 1,000 个随机数并创建直方图。

X = randn(1000,1);

h = histogram(X)

使用 morebins 函数粗略调整 bin 数量。

Nbins = morebins(h);

Nbins = morebins(h)

4.指定直方图bin的边界

生成 1,000 个随机数并创建直方图。将 bin 边界指定为向量,使宽 bin 在直方图的两边,以捕获不满足 的离群值。第一个向量元素是第一个 bin 的左边界,而最后一个向量元素是最后一个 bin 的右边界。

x = randn(1000,1);

edges = [-10 -2:0.25:2 10];

h = histogram(x,edges);

将 Normalization 属性指定为 ‘countdensity’ 以使包含离群值的 bin 扁平化。现在,每个 bin 的区域(而不是高度)表示该 bin 的观测值频率。

h.Normalization = 'countdensity';

5.绘制分类直方图

创建一个表示投票的分类向量。该向量中的类别是 ‘yes’、‘no’ 或 ‘undecided’。

A = [0 0 1 1 1 0 0 0 0 NaN NaN 1 0 0 0 1 0 1 0 1 0 0 0 1 1 1 1];

C = categorical(A,[1 0 NaN],{'yes','no','undecided'})

h = histogram(C,'BarWidth',0.5)

6.具有指定归一化的直方图

生成 1,000 个随机数并使用 ‘probability’ 归一化创建直方图。

x = randn(1000,1);

h = histogram(x,'Normalization','probability')

7.调整直方图属性

准确指定bin数量

x = randn(1000,1);

h = histogram(x)

h.NumBins = 15;

通过向量指定 bin 边界。向量中的第一个值是第一个 bin 的左边界。最后一个值是最后一个 bin 的右边界。

x = randn(1000,1);

h = histogram(x)

h.BinEdges = [-3:3];

8.确定基本概率分布

x = 2*randn(5000,1) + 5;

histogram(x,'Normalization','pdf')

对于均值为 5、标准差为 2 的正态分布,叠加一个概率密度函数图。

x = 2*randn(5000,1) + 5;

histogram(x,'Normalization','pdf')

hold on

y = -5:0.1:15;

mu = 5;

sigma = 2;

f = exp(-(y-mu).^2./(2*sigma^2))./(sigma*sqrt(2*pi));

plot(y,f,'LineWidth',1.5)

9.Matlab中更改直方图颜色

x = randn(1000,1);

h = histogram(x)

h.BinEdges = [-3:3];

h.FaceColor = [0 0.8 0.5];

h.EdgeColor = 'm';

10.Matlab中绘制多个直方图histogram函数

生成两个随机数向量并在同一图窗中针对每个向量绘制对应的一个直方图。

x = randn(2000,1);

y = 1 + randn(5000,1);

h1 = histogram(x);

hold on

h2 = histogram(y);

由于直方图的示例大小和 bin 宽度不同,很难将它们进行比较。对这些直方图进行归一化,这样所有的条形高度相加的结果为 1 并使用统一的 bin 宽度。

h1.Normalization = 'probability';

h1.BinWidth = 0.25;

h2.Normalization = 'probability';

h2.BinWidth = 0.25;