How can I base my legend on the markers I defined in my plot?

60 ビュー (過去 30 日間)
Thys Scholten
Thys Scholten 2019 年 9 月 11 日
回答済み: Rik 2019 年 9 月 11 日
I have a large data set form wich I want to plot quite some graphs, 105 to be exacly. In these graphs a maximum of 4 lines is plotted but not in every graph. I have added a maker and a line color so that they are easy to diffentiate for eachother. I want to add a legend to these so that you can see which line is what. The legend however get, I think, overruled when a new line is added and if I add the legend at the end of my code it wil not refer to te right line if not all the 4 lines are in the graph. Is it possible to create a legend based on the linecolor of on the marker?
if Config_num(a,1) ~= Configuration(c-1,1) && Config_num(a,1) == Configuration(c,1)
n= sum(Configuration == Config_num(a,1));
plot(Fn(c:c+n-1,1),Rel_rest(c:c+n-1,1),'-bo')
T = {'Lp/Bpx =' LpBpx(c,1) , 'Ap/\Nabla =' ApNabla23Rounded(c,1) , 'LCG =' LCG(c,1)};
legend('\beta = 12.5', 'Location', 'northwest');
title(T)
elseif Config_num(a,2) ~= Configuration(c-1,1) && Config_num(a,2) == Configuration(c,1)
n= sum(Configuration == Config_num(a,2));
plot(Fn(c:c+n-1,1),Rel_rest(c:c+n-1,1),'-rx')
legend('\beta = 19', 'Location', 'northwest');
title(T)
elseif Config_num(a,3) ~= Configuration(c-1,1) && Config_num(a,3) == Configuration(c,1)
n= sum(Configuration == Config_num(a,3));
plot(Fn(c:c+n-1,1),Rel_rest(c:c+n-1,1),'-cs')
legend('\beta = 25', 'Location', 'northwest');
title(T)
elseif Config_num(a,4) ~= Configuration(c-1,1) && Config_num(a,4) == Configuration(c,1)
n= sum(Configuration == Config_num(a,4));
plot(Fn(c:c+n-1,1),Rel_rest(c:c+n-1,1),'-m^')
legend ('\beta = 30', 'Location', 'northwest');
title(T)
end

採用された回答

Rik
Rik 2019 年 9 月 11 日
The best solution is to set the DisplayName property when calling plot, and/or use an array of handles to create the legend. See the examples below.
x=linspace(0,10,50);
y1=5*cos(x)+rand(size(x));
y2=4*sin(x)+rand(size(x));
y1a=y1+0.5*rand(size(x));
y1b=y1-0.5*rand(size(x));
figure(1),clf(1)%only use clf during debugging
%example 1:
subplot(1,3,1)
plot(x,y1,'DisplayName','foo'),hold on
plot(x,y2,'DisplayName','bar'),hold off
legend
%example 2:
subplot(1,3,2)
h1=plot(x,y1);hold on
h2=plot(x,y2);hold off
legend([h1 h2],{'foo','bar'})
%example 3:
subplot(1,3,3)
h1=plot([x;x]',[y1a;y1b]');hold on
h2=plot(x,y2);hold off
legend([h1(1) h2(1)],{'foo','bar'})

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by