同一图中4组数据的直方图

时间:2016-04-06 11:14:10

标签: matlab image-processing

我需要绘制四个直方图,这些直方图是在单个图中为四个数据集获得的。这是我的代码

s =  [ 2 4 6 8 10  3 2 5 6 8 10 3 3 4];
p = [ 2 4 6 8 10  3 2 5 6 8 10 3 3 4];
q = [ 2 4 6 8 10  3 2 5 6 8 10 3 3 4];
v = [ 2 4 6 8 10  3 2 5 6 8 10 3 3 4];
[series1,centers] = hist(s);
[series2] = hist(p,centers);
[series3] = hist(q,centers);
[series4] = hist(v,centers);
DataSum=series1+series2+series3+series4;
figure;
width1 = 0.5;
bar(centers,DataSum,width1,'FaceColor',[0.2,0.2,0.5],'EdgeColor','none');
hold on
width2 = width1;
bar(centers,series2,width2,'FaceColor',[0,0.7,0.7],'EdgeColor',[0,0.7,0.7]);
width3 = width2;
bar(centers,series3,width3,'FaceColor',[0.4,0.4,0.6],'EdgeColor',[0.4,0.4,0.6]);
width4 = width3;
bar(centers,series4,width4,'FaceColor',[0,0.9,0.9],'EdgeColor',[0,0.9,0.9]);
hold off
legend('First Series','Second Series', 'Third Series','Fourth Series') % add legend

但问题是它给了我两种颜色的直方图,而不是用四种颜色显示直方图。提前谢谢

1 个答案:

答案 0 :(得分:4)

构建堆积条形图

您好像正在寻找堆积条形图而不是4个单独的条形图(相互覆盖“覆盖”)。

您可以使用单个bar图表绘制此类堆积图表,方法是添加'stack'选项。

(编辑)的

  

“是的,我需要条形图,在添加不同颜色后重新表示所有4个矩阵的数据。”

W.r.t。这个评论,我从你的例子中删除了明确的DataSum,因为特定值的不同条形的总和将通过堆积条的总高度显而易见。

%// data series
s =  [ 2 4 6 8 10  3 2 5 6 8 10 3 3 4];
p =  [ 2 4 6 8 10  3 2 5 6 8 10 3 3 4];
q =  [ 2 4 6 8 10  3 2 5 6 8 10 3 3 4];
v =  [ 2 4 6 8 10  3 2 5 6 8 10 3 3 4];
[s1,centers] = hist(s);
[s2] = hist(p,centers);
[s3] = hist(q,centers);
[s4] = hist(v,centers);

%// stacked bar chart
barWidth = 0.5;
b = bar(centers, [s1' s2' s3' s4'], barWidth, 'stack');
ylim([0, 14]);
legend('First Series','Second Series', 'Third Series','Fourth Series')

%// customize bars (Matlab version >= R2014b)
b(1).FaceColor = [0.2,0.2,0.5];
b(1).EdgeColor = [0.2,0.2,0.5]; %// same as face (as compared to your 'none')
b(2).FaceColor = [0,0.7,0.7];
b(2).EdgeColor = [0,0.7,0.7];
b(3).FaceColor = [0.4,0.4,0.6];
b(3).EdgeColor = [0.4,0.4,0.6];
b(4).FaceColor = [0,0.9,0.9];
b(4).EdgeColor = [0,0.9,0.9];

%// or, use 'set' to customize bars (works for Matlab version < 2014b)
% NameArray = {'FaceColor','EdgeColor'};
% set(b(1),NameArray,{[0.2,0.2,0.5],[0.2,0.2,0.5]})
% set(b(2),NameArray,{[0,0.7,0.7],[0,0.7,0.7]})
% set(b(3),NameArray,{[0.4,0.4,0.6],[0.4,0.4,0.6]})
% set(b(4),NameArray,{[0,0.9,0.9],[0,0.9,0.9]})

产生以下条形图

enter image description here

另请参阅bar命令的语言参考: