MATLAB Answers


multi bar labeling plot

Asked by Ali Ali on 16 May 2019 at 21:26
Latest activity Commented on by Ali Ali about 5 hours ago
I want to label each three bars as p1, p2 and p3 for all at the base as the pic attached.. i appreciate any help someone can provide.


Adam Danz
on 16 May 2019 at 22:32
Wouldn't a legend defining the colors make more sense?
Ali Ali on 16 May 2019 at 22:37
you are right.. but i'll manopolate with the colors later.. so it will not be fixed as it now.

Sign in to comment.

2 Answers

Answer by Adam Danz
on 16 May 2019 at 23:22
Edited by Adam Danz
on 16 May 2019 at 23:33
 Accepted Answer

Here's how to locate the center of each grouped bar and label them. It uses an undocumented property "XOffset". This was developed and tested in r2019a.
xCnt are the bar centers.
% Generate grouped bar plot
v = randi(20,12,3);
h = bar(v,.8);
% Get group centers
xCnt = get(h(1),'XData') + cell2mat(get(h,'XOffset')); % XOffset is undocumented!
% Create Tick Labels
xLab = repmat({'p1','p2','p3'},1,numel(xCnt)/3);
% Set individual ticks
set(gca, 'XTick', sort(xCnt(:)), 'XTickLabel', xLab)
Alternatively, you could rotate the x tick labels
set(gca, 'XTick', sort(xCnt(:)), 'XTickLabel', xLab, 'xticklabelrotation', 90)
% Or use xtickangle():
The best solution would be to use a legend


Ali Ali on 19 May 2019 at 2:26
like below if you can Adam
Adam Danz
about 13 hours ago
% xLab are the labels for each individual bar. The pattern you want is the following:
% for every odd triplet, you want [nothing, #, nothing]
% and for every even triplet you want [p#, p#, p#].
% We already have the p# labels so we just need to alter the odd number groups.
% Step 1) Identify the odd number groups.
isOdd = repmat(logical([1,1,1,0,0,0]),1,length(xLab)/6);
% Step 2) Create new labels
newLabs = strsplit(sprintf('| |%d| |', 1:2:length(xLab)/3),'|');
newLabs(cellfun(@isempty, newLabs)) = [];
% Step 3) replace the p# labels for odd groups with [nothing, #, nothing]
xLab(isOdd) = newLabs;
% Step 4) assing newlabels to plot
set(gca, 'XTick', sort(xCnt(:)), 'XTickLabel', xLab, 'xticklabelrotation', 90)
thank you a lot Adam.. this is realy helped me.

Sign in to comment.

Answer by Sulaymon Eshkabilov on 16 May 2019 at 23:03

Hi Ali,
Here is a simple solution to your problem:
A= randi([15, 25], 13, 3); % Insert your data here
H = bar(A); shg
Good luck.


Adam Danz
on 16 May 2019 at 23:23
How does that solve his problem?
Ali Ali on 17 May 2019 at 0:00
Sulaymon Eshkabilov i think you did not get my point.. anyway thank you for your help.

Sign in to comment.