How to select specific legend entries for bar chart
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Hannah Sargeant
am 27 Feb. 2017
Beantwortet: Tiago Dias
am 4 Jun. 2019
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/161150/image.jpeg)
% 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 Kommentare
Akzeptierte Antwort
Rik
am 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
Weitere Antworten (1)
Siehe auch
Kategorien
Mehr zu Annotations finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!