File Exchange Pick of the Week

Our best user submissions

Create Multi-Column Plot Legends

Brett's Pick this week is "columnlegend," by Simon Henin.

NOTE: Functionality similar to this File Exchange entry was added to MATLAB in R2018a. See the NumColumns Property to legend.

Today's Pick is another that is an author's first submission to the File Exchange. Simon shared a nice, easy-to-use function to create multi-column figure labels.

MATLAB's built-in legend command suffices for most cases when there are few objects to differentiate. However, when the number of lines plotted, for instance, gets large, columnlegend shines. It enables one essentially to reshape the default n-by-one legend into a p-by-q one.

Consider:

nLines = 18;
legend_str = cell(nLines,1);

myColors = distinguishable_colors(nLines);

(See my previous post about distinguishable_colors, or comment out the above line, and uncomment the following one.)

%myColors = jet(nLines);
t = 0:pi/64:3*pi;
dPhi = pi/16;
lineStyles = {'-', '--', ':', '-.'};
for ii=1:nLines,
    plot(t,sin(t+dPhi*ii),...
        'linestyle', lineStyles{rem(ii-1,numel(lineStyles))+1},...
        'color', myColors(ii,:),...
        'linewidth',3);
    hold on;
    legend_str{ii} = num2str(ii);
end
axis([0 3*pi -1.15 1.6])
legend(legend_str,'location','NorthWest')

Now consider how columnlegend improves the situation:

for ii=1:nLines,
    plot(t,sin(t+dPhi*ii),...
        'linestyle', lineStyles{rem(ii-1,numel(lineStyles))+1},...
        'color', myColors(ii,:),...
        'linewidth',3);
    hold on;
    legend_str{ii} = num2str(ii);
end
axis([0 3*pi -1.15 1.6])
columnlegend(6,legend_str,'NorthWest');

That's better! columnlegend also conveniently provides a handle to the legend-containing axes, allowing you to tweak parameters (like position). Very nice first effort, Simon!

One further note: in a comment on his submission page, Simon mentioned that he had fixed an issue with plot markers. As of this writing, that modification is still pending; it should be available shortly.

Let us know what you think, or leave a comment for Simon here.




Published with MATLAB® 7.11

|
  • print

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.