Histogram of 2 sets of data in same plot, different columns, same bin

56 vues (au cours des 30 derniers jours)
Aboma
Aboma le 16 Mai 2014
Hello,
I have been searching for quite some time now for an answer to this question. How can I create a histogram of two sets of data where each set has a different color? All the answers I have found shows how I can overlay two histograms, but I want each bin to show two columns with different colors.
Example 4 on the following page http://www.mathworks.se/help/symbolic/mupad_ref/plot-bars2d.html does exactly what I want (but shown with 3 sets of data). However, this is for MuPAD. How can I do this in Matlab?
To describe in more detail:
I have:
-P1 and P2 who are the two data sets (1x1000 vectors). -I set a vector v=-30:30 that I use for binning both in the following way:¨
[n1,p1]=hist(P1,v)
[n2,p2]=hist(P2,v)
Then if I use the bar command together with 'hold on', I get two histograms where the columns overlap.
bar(p1,n1);hold on; bar(p2,n2,'facecolor','r')
I want them to be side by side for each column.
Thank you for your help!
  1 commentaire
Diemo Schwarz
Diemo Schwarz le 7 Juin 2016
hist([P1, P2]) should group your data.
However, this functionality seems to be lost in the new histogram function.

Connectez-vous pour commenter.

Réponses (4)

Chad Greene
Chad Greene le 14 Août 2014
Instead of plotting the bars side by side, have you considered plotting them on top of each other and adjusting transparency? Transparency is easily set with histf.

Amir
Amir le 15 Août 2014
Modifié(e) : Amir le 15 Août 2014
Please try this code, I have modified this .
clc
clear
close all
nbins=20;
series1 = [10,25,90,35,16, 8, 25, 55, 55];
series2 = [7,38,31,50,41,25,90,35,16];
[series1,centers] = hist(series1,nbins);
[series2] = hist(series2,centers);
DataSum=series1+series2;
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]);
hold off
legend('First Series','Second Series') % add legend

dpb
dpb le 16 Mai 2014
bar([p1;p2],[n1;n2],'grouped')
doc bar % look at example under "Bar Graph Styles"

yousra boukaissi
yousra boukaissi le 6 Juin 2022
figure hist ([P1 P2])

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by