Legend command creates too many entries

How do I get the legend to only have a few of the plots and not all of them? I try plotting two plots, creating a legend for the two plots, and then I add another plot and it automatically goes in the legend as 'data1'. How do I not have the last plot in my legend?
Reproduction steps:
>> plot(1:10)
>> hold on
>> plot(1:3:12)
>> legend('plot1', 'plot2')
>> plot(1:2:16)

 Accepted Answer

Putting the legend at the end of all the plots resolves this issue.
>> plot(1:10)
>> hold on
>> plot(1:3:12)
>> plot(1:2:16)
>> legend('plot1', 'plot2')
The legend automatically will only include the number of plots that are included in the legend definition. If plots are added after the legend is created, MATLAB assumes you want those included in your legend and will automatically put them in labeled as 'data1', 'data2', ...
If you would like MATLAB to include a subset of your plots that are not the first consecutive plots, these can be specified as described in the following link:

1 Comment

It's good practice to explicitly give the plot handles to legend.
h1 = plot(t1,(X1),'r',t3,(X3)-S,'r:');
hold on
h2 = plot(tt2,(X),'-g',tt4,(Z)-S,'-b');
% for sake of description, i used different labels
legend([h1; h2],{'x1 vs t1','x3 vs t3','x vs tt2','z vs tt4'})
Similarly, you have four plot objects, so maybe consider that you might need four labels instead of two.
If for some reason, you only want the legend to represent the last two plots, then just give it those handles.
legend(h2,{'x vs tt2','z vs tt4'},'location','northwest')

Sign in to comment.

More Answers (0)

Products

Release

R2017a

Community Treasure Hunt

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

Start Hunting!