Clear Filters
Clear Filters

Overlay and group two (or more) bar graphs (value by value)

2 views (last 30 days)
Hi. I need to create a graph by overlapping and grouping the values on the vertical axis of two graphs I have generated:
load CountArray_A
load CountArray_S
x_A = CountArray_A(:,1).';
y_A = CountArray_A(:,2);
figure();
graph_A = barh(x_A,y_A,'FaceColor',[1 0 0],'EdgeColor','none');
name_A = "analysis A";
legend({name_A},'Location','northeast','Orientation','horizontal')
x_S = CountArray_S(:,1).';
y_S = CountArray_S(:,2);
figure();
graph_S = barh(x_S,y_S,'FaceColor',[0 1 0],'EdgeColor','none');
name_S = "analysis S";
legend({name_S},'Location','northeast','Orientation','horizontal')
The overall figure I would like to get should look like this (applied to my case, of course):
p.s. It could also happen, I don't know if this is a case, that a value present on the vertical axis is not present in one graph (but present in the other). In this case there would be only one bar (and not two) at the number present on the vertical axis.

Accepted Answer

Star Strider
Star Strider on 2 Aug 2023
Try this —
LD1 = load('CountArray_A.mat');
LD2 = load('CountArray_S.mat');
CountArray_A = LD1.CountArray_A;
CountArray_S = LD2.CountArray_S;
C(:,1) = (min([CountArray_A(:,1); CountArray_S(:,1)]) : max([CountArray_A(:,1); CountArray_S(:,1)])).';
C(:,[2 3]) = zeros(size(C(:,1),1),2);
LvA = ismember(C(:,1), CountArray_A(:,1));
LvS = ismember(C(:,1), CountArray_S(:,1));
C(LvA,2) = CountArray_A(:,2);
C(LvS,3) = CountArray_S(:,2);
figure
hbh = barh(C(:,1), C(:,[2 3]));
cm = [1 0 0; 0 1 0];
for k = 1:numel(hbh)
hbh(k).FaceColor = cm(k,:);
hbh(k).EdgeColor = 'none';
end
legend('Analysis A', 'Analysis S', 'Location','best')
It first creates a common ‘x’ vector and then fills the last two columns of the ‘C’ matrix with appropriate values from the two ‘count’ vectors using a ‘logical indexing’ approach with the logical indices created by the ismember calls.
.

More Answers (0)

Categories

Find more on Discrete Data Plots in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!