MATLAB: How to make a legend for data organized into colours in a bar plot

bar graphlegendMATLAB

Hello, I have data (see attached figure) which is grouped together by colour. I would like to have a legend that which explains what each colour grouping is defined by. I can only find legend creation questions about creating legends on the actual x-axis data, instead of the colour by which I organized it.
Is there a way to do this? I organized my data by colour as follows:
for i = 1:length(Names)
switch Names(i)
case{'Pu','Am','Np','Cm'}
Yield.CData(i,:) = [255 0 0];
case{'Mo','Ru','Tc','Rh','Zn','Ga'}
Yield.CData(i,:) = [0 255 0];
case{'Ce','Nd','Eu','Sm','Sc','Y','La'}
Yield.CData(i,:) = [255 255 0];
case{'Li','Na','K','Rb','Cs','Fr'}
Yield.CData(i,:) = [0 0 0];
case{'O','Xe','Te'}
Yield.CData(i,:) = [255 255 255];
end
end
If someone could provide an answer or some insight I would greatly appreicate it.
~ Dan

Best Answer

OK, with your data file...
[Yield,Elements] = xlsread('test.xlsx');
[YS,iY]=sort(Yield,'descend'); % index to plot by size
FigureName = '';XaxisLabel ='Element';YaxisLabel='Yield (atomic %)';
hF=figure('Name',FigureName,'color','white');
hBY = bar(YS); % use different, identifiable variable for handle
hBY.FaceColor = 'flat';
for i = 1:length(Elements)
switch Elements{iY(i)} % get in sorted order
case{'Pu','Am','Np','Cm'}
hBY.CData(i,:) = [255 0 0]; % red for actinides
case{'Mo','Ru','Tc','Rh','Zn','Ga'}
hBY.CData(i,:) = [0 255 0]; % green for noble metals
case{'Ce','Nd','Eu','Sm','Sc','Y',}
hBY.CData(i,:) = [0 0 255]; % blue for lanthanides (R.E.E.)
case{'Li','Na','K','Rb','Cs','Fr'}
hBY.CData(i,:) = [0 0 0]; % black for alkali-metal halides
case{'O','Xe','He','Ne','Ar','Kr',}
hBY.CData(i,:) = [255 255 255]; % white for non-metals

end
end
hAx=gca; % axes handle for munging with
hAx.XTick=1:numel(Y);
hAx.XTickLabel=Elements(iY);
hAY.YAxis.TickLabelFormat='%0.3f'; % set consistent format string
xlabel('Element','FontName','Optima','FontSize',10);
ylabel('Yield (atomic %)','FontName','Optima','FontSize',10);
title('Yield by Element Classification','FontName','Optima','FontSize',16);
% Now add dummy bar plot to make legends match colors
hold on
% colors -- desired color for each type/class
%co=get(groot,'defaultAxesColorOrder'); % get current axes color order
colors=[[1 0 0]; ... % red for actinides
[0 1 0]; ... % green for noble metals
[0 0 1]; ... % blue for lanthanides (R.E.E.)
[0 0 0]; ... % black for alkali-metal halides
[1 1 1]]; % white for non-metals
nColors=size(colors,1); % make variable so can change easily
labels={'Actinide';'Noble metal';'Lanthanide';'Alkali halide';'Non-metal'};
hBLG = bar(nan(2,nColors)); % the bar object array for legend
for i=1:nColors
hBLG(i).FaceColor=colors(i,:);
end
hLG=legend(hBLG,labels,'location','northeast');
producesuntitled.jpg
Related Question