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)
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 huntitled.jpgave been clear

Sign in to comment.

Accepted Answer

Bruno Luong
Bruno Luong on 17 Aug 2019
Elena Casiraghi
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!

Sign in to comment.

More Answers (1)

Walter Roberson
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, :) ;
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.


Community Treasure Hunt

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

Start Hunting!