How to select specific legend entries for bar chart

2 次查看(过去 30 天)
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

采纳的回答

Rik
Rik 2017-2-27
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

更多回答(1 个)

Tiago Dias
Tiago Dias 2019-6-4
Hi, what is extraction?

类别

Help CenterFile Exchange 中查找有关 Annotations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by