I have a Figure file where I would like to change the order of the entries (e.g., put the first entry as third one). I saved this Figure.fig long time ago so I am not sure if I can recover the original code.
Here I show you my plot:
I want the legend elements to be in a decreasing order ( as in the picture) but due to a mistake my second entry is referring to the wrong plot (it says "25 years" but the plot is actually referred to the lowest trend, corresponding to the "9 years" trend).
Can I switch the order of the entries in the Legend directly from the Properties Editor of the Figure in Matlab? If yes, how (I did not see any "Order" property or similar)? Otherwise is there any other simple approach to switch the order of the entries in the Legend?
If your figure was generated in R2014b or newer you can utilize the undocumented 'PlotChildren'
property to manipulate the order of the legend entries without requiring a new legend
call.
For example:
x = 1:10;
y1 = x;
y2 = 2*x;
y3 = 3*x;
y4 = x.^2;
plot(x, y1, x, y2, x, y3, x, y4);
lh = legend('y = x', 'y = 2*x', 'y = 3*x', 'y = x.^2');
Produces:
Which you can then manipulate:
neworder = [3, 1, 4, 2];
lh.PlotChildren = lh.PlotChildren(neworder);
Producing:
If you don't have the handle to the legend
object, it is a child of the figure
object containing the axes
object your data is plotted on. You can find the handle to your legend
object using one of the following findobj
approaches:
% Handle to figure object known
lg = findobj(figureobj, 'Type', 'legend');
% Handle to figure object unknown
lh = findobj(gcf, 'Type', 'legend');
Note that gcf
generally returns the handle to the last figure that the user clicked on, but this is not necessarily always the case.
Self promotion edit: This method is included in a set of legend manipulation tools maintained on GitHub by the StackOverflow MATLAB community.