How do I set the legend to display only one entry for all line plots of same color in MATLAB?

18 vues (au cours des 30 derniers jours)
When I execute the following code,
plot(1:10,sin(1:10),'r');
hold on
plot(1:10,cos(1:10),'r');
plot(1:10,sin(1:10) + sin(1:10),'b');
a figure with three line plots appears. Two of the line plots are colored red and the other is colored blue. When I insert a legend in my figure, I observe two red lines labeled 'data1' and 'data2' and the blue line labeled 'data3' in the legend box. However, I wish to see only one entry for red line labeled as 'data1' and the blue line to be labeled 'data2'. How can I suppress legends with duplicate symbolization?

Réponse acceptée

MathWorks Support Team
MathWorks Support Team le 22 Déc 2009
In order to display only one entry for red line labeled as 'data1' (though associated with two of the three line plots) and one entry for blue line labeled as 'data2', you need to invoke the LEGEND function with the handles of just those line objects that you wish to display in the legend. Modifying the sample code in the following way displays the legend as desired:
h(1) = plot(1:10,sin(1:10),'r');
hold on
h(2) = plot(1:10,cos(1:10),'r');
h(3) = plot(1:10,cos(1:10) + sin(1:10),'b');
legend(h([1,3]),{'data1','data2'})
  1 commentaire
KAE
KAE le 17 Mar 2017
Modifié(e) : KAE le 17 Mar 2017
Note that if you subsequently plot another line after the example code, such as
plot(1, 7, 'r*')
legend updates with 'data3' as an unwanted new entry (R2017a). As a workaround, execute the legend call after all plotting calls are done: If you specify the line handle then, legend will only label those lines,
legend(h([1,3]),{'data1','data2'})

Connectez-vous pour commenter.

Plus de réponses (0)

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by