フィルターのクリア

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 件のコメント
Hannah Sargeant
Hannah Sargeant 2017 年 3 月 1 日
That's great! Thank you very much

サインインしてコメントする。

その他の回答 (1 件)

Tiago Dias
Tiago Dias 2019 年 6 月 4 日
Hi, what is extraction?

カテゴリ

Help Center および File ExchangeBar Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by