# How can I set the colors in the legend if I show a number of legend elements which is lower thatn the number of plotted functions?

2 views (last 30 days)
Elena Casiraghi on 17 Aug 2019
Commented: Elena Casiraghi on 18 Aug 2019
Dear, I'm trying to do a bar chart as the attached one (and shown below).
As you can see, the bar chart contains, for six different number of k (kNN imputation) the class separation for 22 features.
Then I have: group one with 22 features (for k=5), group two with 22 features (for k=4),... end so on.
You can notice that the color helps identifying features through different ks.
Now the problem is with the legend.
I don't want to repeat feat 1feat2 feat3 .... feat22 for six times, so I would like to have the legen showing feat1,..., feat22 just ones.
I can do it but the problem is that the legend color for feati (where i>1) does not match the bar color. In the legen the color are just blues.
How can I do that? I hope I have been clear
Elena Casiraghi on 17 Aug 2019
results is this ( as you can see legends are blue)

Bruno Luong on 17 Aug 2019
h=bar(rand(10,3))
legend(h(1:3),'1','2','3')
Elena Casiraghi on 17 Aug 2019
Dear Bruno,
sorry but copying generated the mess.
Indeed, my data is 6x66 and feature and featureNameMean is a cell array 1x66.
but anyhow, it's correct now, thanks a lot!

Walter Roberson on 17 Aug 2019
The trick for custom legends is to use
for k = 1:num2show
bh(k) = bar(nan, 'color', BarColors(k, :) ;
end
legend(bh, BarLegends)
Where BarColors is an nx3 array of colors to use and BarLegends is a cell array of character vectors giving the corresponding text.
The way this works is that the nan data points tell bar() not to draw anything, but a graphics handle is created and its properties can be manipulated. You legend() those handles and it puts up the corresponding entry even though there are no visible data points for it.
Elena Casiraghi on 18 Aug 2019
Thanks Walter!