How could I set the legend for a particular bar in a bar chart?

160 views (last 30 days)
I have a bar chart describing 22 groups of data (from the year 1997 to 2018), each group has 10 elements (see the below fig), now I want to set a legend for the 7th bar of year 2004 (a purple bar), how could I do that? Thanks a lot..
  2 Comments
Artur Zych
Artur Zych on 29 Aug 2020
How did you get the bar of year 2004 to be a purple?
Because I can only get a series to one color

Sign in to comment.

Answers (1)

Adam Danz
Adam Danz on 17 Aug 2019
Edited: Adam Danz on 22 Aug 2019
Assign a name to the "DisplayName" propery of each grouped bar handle. The display name will be used in the legend. Here's an example below.
% This will produce 4 groups of 3 different colored bars
y = [2 2 3; 2 5 6; 2 8 9; 2 11 12];
h = bar(y); % h will have 3 handles, one for each color of bars
% set 3 display names for the 3 handles
set(h, {'DisplayName'}, {'Jan','Feb','Mar'}')
% Legend will show names for each color
legend()
If you'd like to display specific bars in the legend,
legend(h(2:3)) %will only show bars 2 and 3
  2 Comments
Joakim Mørk
Joakim Mørk on 6 May 2020
How would this be excecuted if you had both x-vals and y-vals?
I've tried it out but it doesnt seem to work out:
x = [1 2 3];
vals = [2 3 6; 11 23 26];
b = bar(x,vals);
set(b, {'DisplayName'}, {'Jan','Feb','Mar'}')
legend()
Adam Danz
Adam Danz on 6 May 2020
In my example there are 3 members per groups and I assign 3 labels to the legend.
In your example, there are 2 members per group but you assign 3 lables which wouldn't make sense. I think what you're looking for are x tick lables.
set(gca, 'XTick', 1:3, 'XTickLabels', {'Jan','Feb','Mar'})

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!