MATLAB: How to change the colors in a legend on a bar plot when I change the colors of the bars

barhandle graphicslegendMATLAB

I am having some problems with adapting a legend to a bar plot.
I have changed the colors of the bars, but when creating the legend I just have the option of putting one. When I put more entries I get the message
'Ignoring extra legend entries'
I have found in some other posts a way of putting more extra legends, but the problem is that they all have the same color and I have not found the way to change that!
Here is an example of what I mean:
data = rand(1,12);
def2=3:5;
def3=6:9;
def4=10:12;
index = ones(1,length(data));
index(def2)=2;
index(def3)=3;
index(def4)=4;
bar_h=bar(data);
bar_child=get(bar_h,'Children');
mycolor=[0 1 0;0 0 1;1 0 0;0 1 1];
set(bar_child, 'CData',index);
colormap(mycolor);
In this way I have the bars in the different colors I want. Now I would like to have a legend with four entries specifying the four different colors and the legend (for example) 'a','b','c','d'…
What I have found in other posts is:
ch=repmat(bar_child,1,4);
le={'a','b','c','d'};
legend(ch,le);
But I just get the same color in all the entries!

Best Answer

You cannot do what you want using legend when you use bar() with a row or column vector. Internals of how legends are handled are described in MATLAB documentation.
We can see through examination of your code that only a single barseries object is being produced and it will have only a single patch object as its child. The documentation referenced earlier shows that only a single legend slot is available for this situation. You can get multiple lines for the legend but there is not enough control information available to assign them different colors.
What you should be doing instead is using multiple bar() calls, one per group. You can specify the y values to be associated with the entries so that they will all appear on one graph, and you can legend() the groupings.