File Exchange Pick of the Week

Flexible Legends

Posted by Jiro Doke,

Jiro's pick this week is legendflex by Kelly Kearney.

When I talk to users who are experienced in Handle Graphics, I sometimes get asked about customizing legends. This could be somewhat tricky, especially since legends are axes objects with various callbacks and listeners built in. When I ask what exactly they would want to customize, they mention things like adding titles and tiling legends in different orientations.

Earlier this year, Brett wrote a post highlighting columnlegend which allows you to create legends with multiple columns. Kelly's legendflex takes it one step further and gives you additional flexibility in adding titles and placing multiple legends systematically.

Take a look at this example where I show solutions to a 2nd order ordinary differential equation with varying parameters. The line color and style represent different things, and the multiple legends accurately describe that.

% Define parameters
m = 5;         % mass
b = [0.5 1 2]; % damping
k = [0.5 1 2]; % stiffness

% Define colors and styles
colors     = {[1 0 0], [0 .5 0], [0 0 1]};
linestyles = {'-', '--', ':'};

% Preallocate variable
h = nan(length(k), length(b));

% Simulate for each combination of b and k
for kID = 1:length(k)
   for bID = 1:length(b)
      [T, Y] = ode45(@(t, y) [y(2); -1/m*(k(kID)*y(1)+b(bID)*y(2))], ...
         [0, 25], ...   % simulate for 25 seconds
         [1, 0]);       % initial conditions

      % Plot
      h(kID, bID) = line(T, Y(:, 1), ...
         'LineWidth', 2, ...
         'Color'    , colors{kID}, ...
         'LineStyle', linestyles{bID});
   end
end

ylim([-1.2 1.2]); box on;
xlabel('Time (sec)');
ylabel('Displacement (m)');
title(sprintf(['5x\\prime\\prime + b x\\prime + k x = 0\n', ...
   'x = 1, x\\prime = 0']));

% Create a legend for Damping and place it flush against the corner
[h1, o_h] = legendflex(h(1, :), cellstr(num2str(b')), ...
   'ref', gca, 'anchor', {'ne', 'ne'}, 'buffer', [0 0], ...
   'title', {'Line Style', 'Damping (N-s/m)'});
% Set the color of lines to black
set(o_h, 'Color', 'black');

% Create a legend for Stiffness and place it 10 pixels left of
%        the Damping legend
legendflex(h(:, 1), cellstr(num2str(k')), ...
   'ref', h1, 'anchor', {'nw', 'ne'}, 'buffer', [-10 0], ...
   'title', {'Color', 'Stiffness (N/m)'});

Another thing to note is the well-documented code. Kelly has included extensive help with an example. I'm also happy to see the use of inputParser, validateattributes, and validatestring which are very powerful argument validation tools.

Comments

Give it a try and let us know what you think here or leave a comment for Kelly.


Get the MATLAB code

Published with MATLAB® 7.12

Comments are closed.

These postings are the author's and don't necessarily represent the opinions of MathWorks.