How to select specific legend entries for bar chart

조회 수: 2 (최근 30일)
Hannah Sargeant
Hannah Sargeant 2017년 2월 27일
답변: Tiago Dias 2019년 6월 4일
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에서 Bar Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by