1、首先随机产生一组数据作为例子,在这里,我们随机产生一组数据,并将其圆整为整数,方法是:a=round(10*rand(5,1))
2、接下来,可以用MATLAB的内置函数bar进行绘图,方法是bar(a),在这里,可以自己定义直方图的宽度,系统默认的宽度为0.8,因此,可以依据默认的宽度设置自己想要的宽度,例如,在本例中将宽度设置为0.5,bar(a,0.5)
3、当然除了设置宽度以外,还可以设置直方图的颜色,方法是直接在bar函数的括号里设置就可以了,'r'为红色,'y'为黄色,'b'为黑色等等。bar(a,0.5,'r'),如图。
4、有时候,还需要在直方图的上方显示它的数值,这时可以用text函数进行标记,方法是:
bar(a,0.5)
for i=1:length(a)
text(i,a(i),num2str(a(i)),'VerticalAlignment','bottom',...
'HorizontalAlignment','center','FontSize',9,'color','r','FontWeight','bold')
end
其中,text后面引号中的内容主要代表标记文字的对齐方式、字的颜色、大小、粗细等,其中,对齐方式必须要设置,否则标记的值不会刚好出现在直方图的正上方,
5、除此之外,还可以做以y轴为底的直方图,方法是用barh函数实现,barh(a,0.5),值的标记,颜色修改等等和上面的方法一样。
hist(x,M):将x封装在M个等距的区间(默认M=10)
histc(x,edges):落入edges元素之间的x值的个数
y=[-3,-2,-1,1,3];
x = -2.9:0.5:2.9;
histc(x,y)
n=hist(x)
n=hist(x,4) %这种情况建议用histc()
只需定义
分布密度曲线上的坐标数组
即可实现
[x,n]=hist(X(:),50)
%
x返回横坐标数组-----频数统计的小区间的中点
%
返回纵坐标数组-----各小区间内的频数
plot(x,n)
%画出近似的密度曲线
我不知道你能不能看懂英文,因为Help里面的解释真的非常清楚:
n = hist(Y) bins the elements in vector Y into 10 equally spaced containers and returns the number of elements in each container as a row vector. If Y is an m-by-p matrix, hist treats the columns of Y as vectors and returns a 10-by-p matrix n. Each column of n contains the results for the corresponding column of Y.
n = histc(x,edges) counts the number of values in vector x that fall between the elements in the edges vector (which must contain monotonically nondecreasing values). n is a length(edges) vector containing these counts.