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)

 Akzeptierte Antwort

MathWorks Support Team
MathWorks Support Team am 26 Mär. 2018

1 Stimme

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 Kommentar

DGM
DGM am 22 Mai 2021
Bearbeitet: DGM am 22 Mai 2021
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')

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte

Version

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by