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

156 vues (au cours des 30 derniers jours)
Lin SU
Lin SU le 17 Août 2019
Commenté : Artur Zych le 29 Août 2020
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 commentaires
darova
darova le 17 Août 2019
Can you please attach your script and data?
Artur Zych
Artur Zych le 29 Août 2020
How did you get the bar of year 2004 to be a purple?
Because I can only get a series to one color

Connectez-vous pour commenter.

Réponses (1)

Adam Danz
Adam Danz le 17 Août 2019
Modifié(e) : Adam Danz le 22 Août 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 commentaires
Joakim Mørk
Joakim Mørk le 6 Mai 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 le 6 Mai 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'})

Connectez-vous pour commenter.

Community Treasure Hunt

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

Start Hunting!

Translated by