Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB graph plotting: assigning legend labels during plot

Tags:

legend

matlab

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..?

like image 297
CaptainProg Avatar asked May 24 '12 16:05

CaptainProg


2 Answers

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.

like image 180
Jonathan Dautrich Avatar answered Oct 01 '22 09:10

Jonathan Dautrich


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).

like image 41
tmpearce Avatar answered Oct 01 '22 09:10

tmpearce