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

조회 수: 55 (최근 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 CenterFile Exchange에서 Legend에 대해 자세히 알아보기

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by