How to change the order of the legend in the Matlab version 2019b?
109 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Gopinath Karuppannan
am 29 Okt. 2021
Kommentiert: Gopinath Karuppannan
am 30 Okt. 2021
Hi
I am trying to change the order of legends based upon the user needs. Below is the reference figure and codes (for eg.)
plot([1 2],[15,30])
>> hold on;plot([1 2],[5,35]);
>> hold on;plot([1 2],[40 40],'--k');
How to change the order of legend in the attached figure?
0 Kommentare
Akzeptierte Antwort
Dave B
am 29 Okt. 2021
Bearbeitet: Dave B
am 29 Okt. 2021
With your existing .fig file, grab the line objects and feed them into legend in whatever order you like:
open('check.fig')
kids=findobj(gca,'type','Line');
legend(kids)
% or legend(kids([2 3 1])) if that's the order you like
% or legend(kids,'abc','def','ghi') if you want to update the labels
For a new plot:
figure
h1=plot([1 2],[15,30],'r','LineWidth',2);
hold on;
h2=plot([1 2],[5,35],'b','LineWidth',2);
h3=plot([1 2],[40 40],'--k','LineWidth',2);
ylim([5 50])
legend([h3 h2 h1],'3','2','1')
4 Kommentare
Dave B
am 29 Okt. 2021
You're generally correct in your understanding but everything is upside down from what you described. That's a little confusing. I'd be surprised if that changed since 2019b, so I'm a little puzzled by your graphic above. In any case, you can be unambiguous about it by looking directly at the kids vector (see below) and you can certainly plot every combination (also below).
In general, I expect the first element of the kids vector that I defined above is the last thing plotted, and the last element of the kids vector is the first element plotted.
open('check.fig');
% I'm removing the semicolon so we can see what's in kids
% If you wanted to check these values programatically, you could use
% get(kids,'DisplayName') to get their 'names' or you can get some
% other aspect of them that you'd like to use to guide their order
kids=findobj(gca,'type','Line')
orig=gca;
Here's a look at all the combinations of orders:
figure;
t = tiledlayout(2,3);
p=perms([1 2 3]);
for i = 1:height(p)
h=copyobj(orig,t);
h.Layout.Tile=i;
kids=findobj(h,'type','Line');
legend(h,kids(p(i,:)));
title(h,sprintf('[%d %d %d]',p(i,:)))
end
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Legend finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!