how to change order of legends?

789 visualizaciones (últimos 30 días)
Mr M.
Mr M. el 23 de Sept. de 2015
Comentada: Muhammad Tauha Ali el 7 de Abr. de 2024
I dont want to change the order of my plots, but I want to change the order in the legend list. How to do?

Respuesta aceptada

Afiq Azaibi
Afiq Azaibi el 29 de Feb. de 2024
Editada: Afiq Azaibi el 1 de Mzo. de 2024
Three ways to change the order of items in the legend
I'll review two ways to flexibly set the legend's order and one way to reverse the legend order.
Flexibly set the legend order:
Let's take this simple example:
figure;
ax = gca;
hold(ax, 'on')
p1 = plot(1:10, LineWidth=5, DisplayName='p1');
p2 = plot(10:-1:1, LineWidth=5, DisplayName='p2');
p3 = plot(ones(10,1)*5, LineWidth=5, DisplayName='p3');
1) The first way is to specify the order the object handles in the legend command. If we wanted p2 on top, p3 in the middle, and p1 on the bottom, we would call this:
legend([p2, p3, p1])
2) The second way you can do this is by updating the child order of the axes. By default, the legend will order the objects in the same order of creation. This is the reverse order of the axes’ Children property since the oldest object gets placed at the bottom:
ax.Children = [p1; p3; p2];
legend;
Note: Updating the order of the Children property will impact the stacking order of the objects in the axes. While you can achieve the same resulting legend as in the first approach, it will alter the appearance in the axes.
Reverse the legend order:
3) Starting in 23b, a new Direction property was added to legend. This property inverts the order of the legend entries. By default, the value of this property is 'normal'.
hold(ax, 'off')
p = plot([1:10; 2:11; 3:12; 4:13]', LineWidth=3);
l = legend;
l.Direction = 'reverse';
Some objects like a stacked bar and area have an inherent order. The legend will set Direction to 'reverse' automatically:
bar(magic(5), 'stacked');
legend;
area(magic(5));
legend;
You can revert back to the previous behavior by specifying the legend's direction to be 'normal'
legend(Direction='normal');
  1 comentario
Shara Gremillion
Shara Gremillion el 10 de Feb. de 2024
Movida: Adam Danz el 1 de Mzo. de 2024
Works great! Thanks.

Iniciar sesión para comentar.

Más respuestas (10)

David
David el 10 de En. de 2018
Editada: David el 10 de En. de 2018
I think Mr. M means the following: In the figure GUI, after one has worked hard to generate a nice figure by combining the outputs of various scripts via copy + paste, how can one change the order of the legend?
In earlier versions of MATLAB, one could achieve this by cutting and repasting traces. They would then reappear at the bottom of the legend. So you would take the trace you want to be second, cut and paste it, then do the same for the third, all the way to the Nth, and then the legend would have the desired order. Now it is no longer possible to do this. The figure somehow remembers the position of the trace before it was cut.
But there is a WORK-AROUND! Simply cut the trace, paste it in onto a different axis of a different figure, then cut that trace and paste it back onto the original figure. This stymies matlab's attempt to remember the order of the trace and puts it onto the bottom of the legend.
  6 comentarios
Walter Roberson
Walter Roberson el 19 de Ag. de 2019
Editada: Walter Roberson el 15 de En. de 2021
fariborz eshraghi
fariborz eshraghi el 5 de Dic. de 2021
That's a wonderful help, thanks.

Iniciar sesión para comentar.


Steven Lord
Steven Lord el 22 de Feb. de 2021
You can specify the handles in a particular order when you create the legend.
% Sample data
x = 0:360;
y1 = sind(x);
y2 = cosd(x);
y3 = tand(x);
% Set up axes
axis([0 360 -1 1])
hold on
% Create plots
h = gobjects(3, 1);
h(1) = plot(x, y1, 'DisplayName', 'sine');
h(2) = plot(x, y2, 'DisplayName', 'cosine');
h(3) = plot(x, y3, 'DisplayName', 'tangent');
% Create legend -- cosine first then sine and finally tangent
legend(h([2 1 3]))

Rick
Rick el 24 de Mzo. de 2018
use this code to swap the order of two plots:
plots=get(gca, 'Children');
legend(plots(2, 1), {'Second line', 'First line'});
  5 comentarios
Walter Roberson
Walter Roberson el 28 de Sept. de 2023
It is not clear what plots is in your code? You are using it as if it is a function or a multidimensional array.
Smart
Smart el 29 de Sept. de 2023
Editada: Smart el 29 de Sept. de 2023
@Walter Roberson Thanks for the catch. I've updated my comment with a line to define plots as it was used above (and fixed the same typo that Rick had)

Iniciar sesión para comentar.


Ed Rawi
Ed Rawi el 22 de Oct. de 2018
Editada: Ed Rawi el 23 de Oct. de 2018
a = linspace(1,10,10);
b1 = sin(a);
Plot1 = plot(a,b1);
hold on
b2 = cos(a);
Plot2 = plot(a,b2);
hold off
legend([plot2 plot1],{Second,First})
  2 comentarios
Jim Bosley
Jim Bosley el 19 de Ag. de 2019
Last line needs plot handles capitalized, as they were defined.
a = linspace(1,10,10);
b1 = sin(a);
Plot1 = plot(a,b1);
hold on
b2 = cos(a);
Plot2 = plot(a,b2);
hold off
legend([Plot2 Plot1],{Second,First})
MCH
MCH el 16 de Dic. de 2020
@Ed: This solution works great

Iniciar sesión para comentar.


Liwei Wang
Liwei Wang el 25 de En. de 2019
Cut+paste is a good idea. But sometimes it won't work because the plots are pretty close to each other. An alternative approach is to change the order of the plots by code:
answered by the cyclist.
Here is the copy of the code:
figure
scatter(rand(150,1),rand(150,1))
hold on
fill([0.2 0.5 0.5 0.2],[0.2 0.2 0.5 0.5],'r')
hg = line([0 0.6],[0.6 0]);
set(hg,'LineWidth',12,'Color','g')
h = get(gca,'Children');
set(gca,'Children',[h(3) h(2) h(1)])
Refresh legend then you will see the change.
  1 comentario
Giorgia Calisti
Giorgia Calisti el 9 de Jun. de 2020
Exactly what I was looking for!
Thank you

Iniciar sesión para comentar.


Kris Govertsen
Kris Govertsen el 15 de En. de 2021
This is how I was able to change the order of the legend on a figure with multiple subplots of area plots:
Before:
I want the order of the legend to follow the order of the colors in the area plot
% a is my figure
% If I type
If I type the following into the command window: a.Children... it returns:
% a.Children
%
% ans =
%
% 5×1 graphics array:
%
% Legend (Grid, VRFB error, VRFB Power, VRFB Energy, LIB error, LIB Power, LIB Energy, Solar, Tidal)
% Axes (Tidal RES)
% Axes (Solar PV RES)
% Axes (VRFB Cost)
% Axes (LIB Cost)
So a.Children(1) is my legend!
% Re-order Legend
lbl = a.Children(1).String; % Retrieve legend labels
numlbl = length(lbl); % Determine number of lables
order = sort(1:1:numlbl,'descend'); % Create array of label numbers in descending order
newlbl = lbl(order); % Create new labels in descending order
legend(findobj(a.Children(2),'Type','area'),newlbl) % Set the legend to follow the new labels
hope this helps!
  2 comentarios
Jan Heinsoth
Jan Heinsoth el 22 de Feb. de 2021
Nice, someone wanted to do the same as me. Thanks
LIU
LIU el 22 de Mzo. de 2022
Hi, I have a silimar problem, and guess your method could be useful for me. But I don't know how to apply your code suited to my case. Would you please kindly have a look at my problem and give me a hand? Thank you very much.
The link is :

Iniciar sesión para comentar.


FM
FM el 22 de Mayo de 2018
There is a good solution in the `Update` section of this post on Stack Overflow: http://stackoverflow.com/a/39104494/3230708

George
George el 23 de Sept. de 2015
Is this something you are after, the question is not clear
x=magic(2);
plot(x(:,1));
hold
plot(x(:,2),'r');
legend('Data1','Data2');
%blue = Data1
%red=Data2
to change that simple reverse the string order
legend('Data2','Data1');

Kris Govertsen
Kris Govertsen el 15 de En. de 2021
This is how I was able to change the order of the legend on a figure with multiple subplots of area plots:
Before:
I want the order of the legend to follow the order of the colors in the area plot
% a is my figure
% If I type
If I type the following into the command window: a.Children... it returns:
% a.Children
%
% ans =
%
% 5×1 graphics array:
%
% Legend (Grid, VRFB error, VRFB Power, VRFB Energy, LIB error, LIB Power, LIB Energy, Solar, Tidal)
% Axes (Tidal RES)
% Axes (Solar PV RES)
% Axes (VRFB Cost)
% Axes (LIB Cost)
So a.Children(1) is my legend!
% Re-order Legend
lbl = a.Children(1).String; % Retrieve legend labels
numlbl = length(lbl); % Determine number of lables
order = sort(1:1:numlbl,'descend'); % Create array of label numbers in descending order
newlbl = lbl(order); % Create new labels in descending order
legend(findobj(a.Children(2),'Type','area'),newlbl) % Set the legend to follow the new labels
hope this helps!

Sandeep A S V
Sandeep A S V el 7 de En. de 2022
Editada: Sandeep A S V el 7 de En. de 2022
There is a simple solution using the property inspector GUI.
1.Go to Edit menu on the figure window
2. Select 'current object properties'
3. Select one of the plots in your figure
4. Change the property 'SeriesIndex' in COLOR AND STYLING tab.
  1 comentario
Muhammad Tauha Ali
Muhammad Tauha Ali el 7 de Abr. de 2024
In 2022b, order can be interactively changed by moving the object order through mouse and updating the series index. The legend will need to be regenerated after the changes though.

Iniciar sesión para comentar.

Community Treasure Hunt

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

Start Hunting!

Translated by