Software/MATLAB

[MATLAB] Figure에서 legend 순서 변경하기

_winmin 2025. 11. 4. 15:20

처음 plot을 그릴 때, plot() 합수의 return object를 받아오면 legend 순서를 변경하기 쉽지만, 이미 그려진 plot의 figure 창에서 plot object도 없을 때 변경하는 법을 기록해두려고 한다. 

x = 1:10;
y1 = x;
y2 = 2*x;
y3 = 3*x;

p1 = plot(x, y1); hold on; % Plot object 저장
p2 = plot(x, y2); hold on;
p3 = plot(x, y3); hold on;

legend([p3,p2,p1], ["3x", "2x", "1x"]);

 

 

figure로부터 plot 한 children 정보를 받아오고 Legend를 다시 표시하는 방식이다. 

load('filename.fig');

labels = get(legend(), 'String');
plots = flipud(get(gca, 'children'));

% Legend 순서 변경
neworder = [3 2 1];
legend(plots(neworder), labels(neworder))

 

(왼) plot 순서대로 그려진 legend (default 순서), (오) Legend 순서 바뀐 figure