Reputation: 315
Consider the following example:
x = magic(3);
figure(1); clf(1);
plot( x, '-r', 'DisplayName', 'Magic' );
legend( 'show' );
The resulting legend entries in MATLAB R2014a are
getcolumn(Magic,1)
getcolumn(Magic,2)
getcolumn(Magic,3)
The problem stems from function [leg,labelhandles,outH,outM] = legend(varargin)
in legend.m
(Copyright 1984-2012 The MathWorks, Inc.), line 628:
str{k} = get(ch(k),'DisplayName');
More specifically, the function get
getcolumn(
and, <Column Number>)
.Is there an easy way to display exactly one legend entry (or multiple, but without the pre- and appended strings) for multiple data rows named after DisplayName
, which have the same visual properties?
An alternative would of course be to programatically create multiple (or one) legend entries through plot handles (see below), but I would like to keep things short and simple.
One entry:
x = magic(3);
figure(1); clf(1);
h = plot( x, '-r' );
legend( h(1), 'Magic' );
Multiple entries:
x = magic(3);
figure(1); clf(1);
h = plot( x, '-r' );
strL = cell( 1, numel(h) );
for k = 1:numel(h)
strL{k} = sprintf( 'Magic %d', k );
end
legend( h, strL );
In MATLAB R2014b, the problem with getcolumn(Name,Row) does not appear anymore for the first code example.
Upvotes: 1
Views: 976
Reputation: 10440
If you want to set multiple display names for the legend entries in short syntax, you just need to prepare a cell array with them, let's say it's called leg_names
, and then use set
to apply them to all at once:
set(p,{'DisplayName'},leg_names);
Let's take a look at an example:
x = magic(3); % your data
p = plot( x,'-r'); % plot and get an array of handles to the lines
% create a list of the desired names for the legend entries:
leg_names = [repmat('Magic ',size(x,2),1) num2str((1:size(x,2)).')];
set(p,{'DisplayName'},cellstr(leg_names)); % set all display names
legend('show'); % show the legend
The result is exactly as in your examples at the end of the question.
Also, note that the syntax: [lgd,icons,plots,txt] = legend(___)
is not recommended (from the docs):
Note: This syntax is not recommended. It creates a legend that does not support all graphics features. Instead, use the
lgd = legend(__)
syntax to return the Legend object and set Legend Properties.
Upvotes: 2