I am plotting data in a typical MATLAB scatterplot format. Ordinarily when plotting multiple datasets, I would use the command 'hold on;', and then plot each of the data, followed by this to get my legend:
legend('DataSet1', 'DataSet2') % etcetera
However, the (multiple) datasets I am plotting on the same axes are not necessarily the same datasets each time. I am plotting up to six different sets of data on the same axes, and there could be any combination of these shown (depending on what the user chooses to display). Obviously that would be a lot of elseif's if I wanted to setup the legend the traditional way.
What I really would like to do is assign each DataSet a name as it is plotted so that afterwards I can just call up a legend of all the data being shown.
...Or, any other solution to this problem that anyone can think of..?
You can try something like the following
Use
'DisplayName'
as aplot()
property, and call your legend asMy code looks like this:
Source: http://undocumentedmatlab.com/blog/legend-semi-documented-feature/
Make a for loop. But Before the for loop, make an array.
One option is to take advantage of the
'UserData'
property like so:Edit: As the questioner pointed out, the original version could get out of order. To fix this, specify which handle goes with which label (in the fixed version, it is in the correct order).
You should be able to set the DisplayName property for each plot:
http://www.mathworks.com/help/matlab/ref/line_props.html
Side Note: I've found a lot of little tricks like this by getting the figure to look the way I want, then choosing the Figure's "File" menu option "Generate M-File..." and inspecting the generated output code.