How do I control the legend contents when the plot functions are within a for loop?

조회 수: 21 (최근 30일)
I'm running into a problem pertaining to legend control in some legacy code. Specifically, how do I suppress the data2 and data4 entries of the legend (in the attached png file) using the following code:
figure('Name', 'Elapsed Time', 'Position', [350 350 610 250] );
hold on;
for FileNum = 1:num_srcs
h1 = plot(data{FileNum}(:, 9), '-*', 'Color', color1{FileNum}, 'DisplayName', disp_name{FileNum} );
%hold on;
h2 = plot( data2{FileNum}(:, 9), '*', 'Color', color1{FileNum} );
%hold off;
%hold off;
legend('location', 'NEO'); % works, but includes the legend entries for data2 and data4
%legend(h1, 'location', 'NEO');
%legend(h1, disp_name{FileNum}, 'location', 'NEO');
set(legend, 'FontSize', 20);
H = gca;
set(H, 'YGrid', 'on', 'GridLineStyle', '-');
box on;
The data2 and data4 data series are the points with no lines (far left side of plot).
In reading the MATLAB documentation and reviewing Aravin's question in January 2012, it appeared the solution was to include only h1 in the legend, using the following line of code;
legend(h1, 'location', 'NEO');
This did not produce the desired result. I've also tried re-locating the hold functions and other legend functions - none have worked.
Is it possible the for loop is adversely affecting the legend function?
Here's the link to Aravin's original question in January 2012:

채택된 답변

Mischa Kim
Mischa Kim 2014년 6월 12일
편집: Mischa Kim 님. 2014년 6월 12일
Brad, see this answer. Or, more closely related to your question:
x = 0:0.1:10;
data1 = sin(x);
data2 = cos(x);
data3 = sin(x).^2;
data4 = cos(x).^2;
p1 = plot(x,data1,'bo-');
hold on
p2 = plot(x,data2,'rx-');
p3 = plot(x,data3,'kd-');
p4 = plot(x,data4,'gs-');
legend([p1,p3],'From data1','From data3');
  댓글 수: 4
Brad 2014년 6월 12일
편집: Star Strider 님. 2014년 6월 12일
Mischa, it appears we found a solution. We added this line of code:
set(get(get(h2, 'Annotation'), 'LegendInformation'), 'IconDisplayStyle', 'off');
after this line of code:
h2 = plot( data2{FileNum}(:, 9), '*', 'Color', color1{FileNum} );
So far, it appears to be running great.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)


Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기


Community Treasure Hunt

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

Start Hunting!

Translated by