How do I set the legend to display only one entry for all line plots of same color in MATLAB?
18 views (last 30 days)
Show older comments
MathWorks Support Team
on 22 Dec 2009
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?
Accepted Answer
MathWorks Support Team
on 22 Dec 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 Comment
KAE
on 17 Mar 2017
Edited: KAE
on 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'})
More Answers (0)
See Also
Categories
Find more on Legend in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!