How can i set legend for different bar with different colors?

4 views (last 30 days)
Hallo
i have a problem with setting legend for different bar with different color. Every bar should be defined with a legend. i have used this code to change the color of bars.
b.FaceColor = 'flat';
b.CData(1,:) = [0 0.4470 0.7410];
b.CData(2,:) = [0.8500 0.3250 0.0980];
b.CData(3,:) = [0.9290 0.6940 0.1250];
b.CData(4,:) = [0.4940 0.1840 0.5560];
b.CData(5,:) = [0.4660 0.6740 0.1880];

Answers (1)

dpb
dpb on 25 Jul 2020
Edited: dpb on 27 Jul 2020
As per usual (despite some much-needed belated improvements on at least being able to label a bar, thanks! TMW) bar is still a royal pain to do much with out of the very limited ideas behind its implementation.
Any vector whether column or row is treated as a single series and ergo has only one bar handle and that means legend can't have more than one entry. You can fool it by trying to be clever and use a group bar with dummy data for the second set, but then it takes a lot of mucking around to fix up the axes...it's not intuitive nor shown in doc how to do it and there are still some manual fixups necessary, but the trick is to draw each bar as a a one-bar barplot...
C=[2100 1800 1200 1200 3200]; % the raw data
figure, hold on % create a figure, set to put more than one plot on axes
hB=arrayfun(@(x,y) bar(x,y),1:numel(C),C); % add numel bars a ordinal position on x axis
xticks(1:numel(C)) % xticks to match bars ordinal positions
xlim([[0 numel(C)+1]+[1 -1]*hB(1).BarWidth/2]) % set so same area at ends of axes (should be default)
box on
hLg=legend(compose('%s',['A':'E'].'),'Location','northwest'); % now have array so can use legend()
There should be an option in bar to do this directly without the extra gyrations, agreed...
ADDENDUM:
BTW, you could use a categorical variable for X and label the bars for free, too...
X=categorical(cellstr(char('A'+[0:numel(C)-1])));
hB=hB=arrayfun(@(x,y) bar(x,y),X,C.');

Community Treasure Hunt

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

Start Hunting!