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

7 views (last 30 days)
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;
end
%hold off;
legend('location', 'NEO'); % works, but includes the legend entries for data2 and data4
%legend(h1);
%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: http://www.mathworks.com/matlabcentral/answers/25381-how-to-show-partial-legend-in-figure

Accepted Answer

Mischa Kim
Mischa Kim on 12 Jun 2014
Edited: Mischa Kim on 12 Jun 2014
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;
figure();
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 Comments
Brad
Brad on 12 Jun 2014
Edited: Star Strider on 12 Jun 2014
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.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!