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?
Another alternative for those using a version of MATLAB older than R2014b is to retrieve the handles to the plot objects by specifying an output to
plot
. You can then re-arrange the handles in the order you want prior to passing them tolegend
.Update
To properly handle when loading from a file, you can get all of the
Children
of the axes to get the plot objects and get the current legend to get the labels. You can then reorder them similar to the above approach.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 newlegend
call.For example:
Produces:
Which you can then manipulate:
Producing:
If you don't have the handle to the
legend
object, it is a child of thefigure
object containing theaxes
object your data is plotted on. You can find the handle to yourlegend
object using one of the followingfindobj
approaches: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.