combining two histograms by category

2 views (last 30 days)
ektor
ektor on 13 Jul 2023
Answered: Voss on 13 Jul 2023
Dear all,
I attach a matlab code that constructs two histograms by category (two categories in total)
I am trying to merge them but
hold on
does not work, which means that there is a bug in my code.
If you could provide some help that would be great.
Note that the first part of the code constructs a histogram by year for caterogory 1.
The second part of the code constructs a histogram by year for caterogory 2.
For the first histogram, the year goes up to 2023.
For the second histogram, the year starts from 2023 up to 2026.
So the second histogram can be easily placed right after the first histogram.
But please note that I want the year 2023 after the merging of the two histograms to be separate for the two catergories; that is I want to have two 2023 years on the x axis.
Hope this helps
Many thanks in advance!

Accepted Answer

Voss
Voss on 13 Jul 2023
Data = readtable('worksheet1.xlsx');
% histogram 1
group1dx = startsWith(Data.mode,'Active');
group1Data = Data{group1dx, 1};
h1 = histogram(group1Data);
group1dx = h1.BinEdges ;
y = h1.Values ;
text(group1dx(1:end-1),y,num2str(y'),'vert','bottom','horiz','center');
% histogram 2
group2dx = startsWith(Data.mode,'NB');
group2Data = Data{group2dx, 1}+1; % Note: add 1 to group2Data to shift it right by one and get duplicate 2023's
hold on
h2=histogram(group2Data);
group2dx = h2.BinEdges ;
y = h2.Values ;
text(group2dx(1:end-1),y,num2str(y'),'vert','bottom','horiz','center');
box off
legend({'Active Fleet: 1,835 Vsls','On Order: 93 Vsls (4.8%)'})
xt = min([group1Data; group2Data]):max([group1Data; group2Data]);
xticks(xt)
% xticklabels are xticks for h1, but for h2 the xticklabels must be adjusted down by 1
xtl = xt;
n_bins_h2 = numel(h2.BinEdges)-1;
xtl(end-n_bins_h2+1:end) = xtl(end-n_bins_h2+1:end)-1;
xticklabels(xtl)

More Answers (0)

Community Treasure Hunt

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

Start Hunting!