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

21 次查看(过去 30 天)
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?

采纳的回答

MathWorks Support Team
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 个评论
KAE
KAE 2017-3-17
编辑:KAE 2017-3-17
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'})

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by