MATLAB Answers

multi bar labeling plot

154 views (last 30 days)
Ali Ali
Ali Ali on 16 May 2019
Commented: Adam Danz on 21 Aug 2021
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.
  2 Comments
Ali Ali
Ali Ali on 16 May 2019
you are right.. but i'll manopolate with the colors later.. so it will not be fixed as it now.

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 16 May 2019
Edited: Adam Danz on 16 May 2019
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
figure()
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(): https://www.mathworks.com/help/matlab/ref/xtickangle.html
The best solution would be to use a legend
legend(h,{'p1','p2','p3'})
  8 Comments
Ali Ali
Ali Ali on 20 May 2019
thank you a lot Adam.. this is realy helped me.

Sign in to comment.

More Answers (2)

Sulaymon Eshkabilov
Sulaymon Eshkabilov on 16 May 2019
Hi Ali,
Here is a simple solution to your problem:
A= randi([15, 25], 13, 3); % Insert your data here
H = bar(A); shg
H(1).FaceColor='g';
H(2).FaceColor='r';
H(3).FaceColor='b';
Good luck.
  1 Comment
Ali Ali
Ali Ali on 17 May 2019
Sulaymon Eshkabilov i think you did not get my point.. anyway thank you for your help.

Sign in to comment.


Sergio Yanez-Pagans
Sergio Yanez-Pagans on 21 Aug 2021
  1 Comment
Adam Danz
Adam Danz on 21 Aug 2021
Cool function, but how does that address the question of how to label the bar groups?

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!