How to select specific legend entries for bar chart
2 views (last 30 days)
Show older comments
I have written a code to produce a bar chart of results. The results have been calculated using 4 different methods and that is how I have coloured the bars. How do I create a legend with just the four colours I have chosen? Instead I can only get the first four entries in the chart, where three of them are the same colour:

% The code is as follows:
figure('name','Extraction energy analysis');
set(gca,'YScale','log')
hold on
for i=1:n
xlabel('Resource')
h=bar(i,output_Q_r(i));
if extraction(i) == 0
set(h,'FaceColor','g');
elseif extraction(i) == 1
set(h,'FaceColor','b');
elseif extraction(i) == 2
set(h,'FaceColor','y');
elseif extraction(i) == 3
set(h,'FaceColor','r');
end
end
hold off
set(gca,'xticklabel',resource)
ylabel('Energy (kW)')
X=(1:16);
XTickLabel=resource;
set(gca,'XTick',X) %assigning number of ticks to number of labels as automatically reaches limit of 15
title(char({'Energy required to extract 1000T of each resource',' from lunar south pole soil in 1 year'}))
xticklabel_rotate([],45)
legend('Thermal gas release',char({'hydrogen reduction',' of ilmenite'}),char({'electrolysis of',' molten regolith'}),'other')
end
0 Comments
Accepted Answer
Rik
on 27 Feb 2017
You can compile a vector of handles and use that as the pointer for legend
h_list=[];
hold on
for i=1:n
xlabel('Resource')
h=bar(i,output_Q_r(i));
if extraction(i) == 0
set(h,'FaceColor','g');
h_list(extraction(i)+1)=h;
elseif extraction(i) == 1
set(h,'FaceColor','b');
h_list(extraction(i)+1)=h;
elseif extraction(i) == 2
set(h,'FaceColor','y');
h_list(extraction(i)+1)=h;
elseif extraction(i) == 3
set(h,'FaceColor','r');
h_list(extraction(i)+1)=h;
end
end
hold off
set(gca,'xticklabel',resource)
ylabel('Energy (kW)')
X=(1:16);
XTickLabel=resource;
set(gca,'XTick',X) %assigning number of ticks to number of labels as automatically reaches limit of 15
title(char({'Energy required to extract 1000T of each resource',' from lunar south pole soil in 1 year'}))
xticklabel_rotate([],45)
legend(h_list,'Thermal gas release',char({'hydrogen reduction',' of ilmenite'}),char({'electrolysis of',' molten regolith'}),'other')
end
More Answers (1)
See Also
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!