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..?
One option is to take advantage of the 'UserData'
property like so:
figure;
hold on
plot([0 1], [1 0], '-b', 'userdata', 'blue line')
plot([1 0], [1 0], '--r', 'userdata', 'red dashes')
% legend(get(get(gca, 'children'), 'userdata')) % wrong
legend(get(gca, 'children'), get(get(gca, 'children'), 'userdata')) % correct
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:
figure
hold on
plot(...,'DisplayName','DataSet1')
plot(...,'DisplayName','DataSet2')
legend(gca,'show')
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.
Use 'DisplayName'
as a plot()
property, and call your legend as
legend('-DynamicLegend');
My code looks like this:
x = 0:h:xmax; %// get an array of x-values
y = someFunction; %// function
plot(x, y, 'DisplayName', 'Function plot 1'); %// plot with 'DisplayName' property
legend('-DynamicLegend',2); %// '-DynamicLegend' legend
Source: http://undocumentedmatlab.com/blog/legend-semi-documented-feature/
You can try something like the following
for k = 1:10
h(k) = plot(...);
name{k} = ['condition ' num2str(k)];
end
legend(h, name);
Make a for loop. But Before the for loop, make an array.
%for example
legendset = {}
for i = 1:10
%blabla
%Then in the fore loop say:
legendset = [legendset;namedata(i)]
%It puts all names in a column of legendset.
%Make sure namedata are characters.
%foreloop ends
end
%Then after the foreloop say:
legend(legendset).