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

displayentrylegendMATLABmultipleselective

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?

Best Answer

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'})