Changing order of legend entries when lslines are included
2 ビュー (過去 30 日間)
古いコメントを表示
Hi, I am using MATLAB 2020a and have a graph that includes a legend with both data labels and lsline labels. I have tried suggestions to reorder the legend from
and here: https://stackoverflow.com/questions/39103748/matlab-change-order-of-entries-in-figure-legend
However, they only seem to address situations where the labels are only coming from the data set(s) in the "plot" command. I have 4 data sets, plus 4 regression lines generated by lsline. The legend entries for lsline are in reverse order, but I can't figure out how to change them.
Here's some code:
figure;
p = plot([1 2;2 1;3 1;1 4]',[1 2;3 1; 4 5;2 4]');
p(1).LineStyle = 'none'; p(1).Marker = 'o'; p(1).MarkerSize = 5;
p(1).MarkerFaceColor = 'b'; p(1).MarkerEdgeColor = 'b'; p(1).DisplayName = '2016 CC';
p(2).LineStyle = 'none'; p(2).Marker = 's'; p(2).MarkerSize = 6;
p(2).MarkerFaceColor = 'b'; p(2).MarkerEdgeColor = 'b'; p(2).DisplayName = '2017 CC';
p(3).LineStyle = 'none'; p(3).Marker = 'o'; p(3).MarkerSize = 5;
p(3).MarkerFaceColor = 'r'; p(3).MarkerEdgeColor = 'r'; p(3).DisplayName = '2016 CS';
p(4).LineStyle = 'none'; p(4).Marker = 's'; p(4).MarkerSize = 6;
p(4).MarkerFaceColor = 'r'; p(4).MarkerEdgeColor = 'r'; p(4).DisplayName = '2017 CS';
h = lsline;
% colors and styles assigned in reverse order - not sure why
h(1,1).LineStyle = '-.'; h(1,1).Color = 'r';
h(1,2).LineStyle = '-'; h(1,2).Color = 'r';
h(1,3).LineStyle = '-.'; h(1,3).Color = 'b';
h(1,4).LineStyle = '-'; h(1,4).Color = 'b';
legend('2016 CC','2017 CC','2016 CS','2017 CS',...
'2017 CS','2016 CS','2017 CC','2016 CC');
Which results in this graph:
The lsline entries are in reverse order, which is reflected in the legend. Rearranging the lsline line assignments would be one fix to my specific issue. But specifically I'm asking how to fix it in the legend.
Thanks in advance.
0 件のコメント
採用された回答
Kelly Kearney
2020 年 12 月 15 日
The easiest way to be certain your legend labels match up is to pass handles specifically:
figure;
p = plot([1 2;2 1;3 1;1 4]',[1 2;3 1; 4 5;2 4]', 'o');
h = lsline;
legend([p' h], '1p','2p','3p','4p','4ls','3ls','2ls','1ls');
The ordering is due to how lsline looks for plotted datasets to regress... it uses get(gca, 'Children'), which always returns plotted objects in reverse stacking order (i.e. top to bottom); in most cases this will mean moving from the most-recently plotted object backwards.
その他の回答 (0 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!