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

57 ビュー (過去 30 日間)
Aboma
Aboma 2014 年 5 月 16 日
回答済み: yousra boukaissi 2022 年 6 月 6 日
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 件のコメント
Diemo Schwarz
Diemo Schwarz 2016 年 6 月 7 日
hist([P1, P2]) should group your data.
However, this functionality seems to be lost in the new histogram function.

サインインしてコメントする。

回答 (4 件)

Chad Greene
Chad Greene 2014 年 8 月 14 日
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 2014 年 8 月 15 日
編集済み: Amir 2014 年 8 月 15 日
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 2014 年 5 月 16 日
bar([p1;p2],[n1;n2],'grouped')
doc bar % look at example under "Bar Graph Styles"

yousra boukaissi
yousra boukaissi 2022 年 6 月 6 日
figure hist ([P1 P2])

カテゴリ

Help Center および File ExchangeSurfaces and Volumes についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by