bajwa77
bajwa77

Reputation: 53

Histogram of 4 sets of data in same plot

I need to plot four histograms which are obtained for four datasets in single plot. here is my code

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

but the problem is it gives me histogram in two colors instead of displaying histogram with four colors. thanks in advance

Upvotes: 0

Views: 86

Answers (1)

dfrib
dfrib

Reputation: 73186

Constructing a stacked bar chart

It seems like you're looking for a stacked bar chart rather than 4 separate bar charts ("overwriting" (covering) each other).

You can plot such a stacked chart using a single bar plot, by including the 'stack' option.

(Edited)

"Yes, I need bar graph that represnts data of all 4 matrices after their addition with different colors."

W.r.t. this comment, I've remove the the explicit DataSum from your example, as the sum of the different bars for a specific value will be apparent by the total height of the stacked bar.

%// 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]})

Yielding the following bar plot

enter image description here

See also the language reference for the bar command:

Upvotes: 4

Related Questions