data99
data99

Reputation: 59

Displaying more than 50 legend entries

I would like to plot 66 datasets and show their legends. Unfortunately, according to the MathWorks Support Team, MATLAB legends are limited by default to 50 entries.

I tried the workaround they suggested that involves making another axes in the plot, copying the previous data, and then hiding the new axes, but I couldn't get it to work (the new axes only shows 1 additional variable from the 16 that are left), and so I'm stuck.

Are there any other ways to display more than 50 legend entries?

Upvotes: 1

Views: 1733

Answers (3)

Dev-iL
Dev-iL

Reputation: 24169

A solution suggested by Eric Sargent (TMW Staff) is to pass the plot handles to the legend command:

p = plot(magic(100));
legend(p);

Note that in this case, the axes are not determined by gca, but instead using ancestor(p, 'axes') (so there's no need to specify the axes handle when calling legend). Moreover, specifying an axes handle makes this solution stop working!

Upvotes: 1

Dev-iL
Dev-iL

Reputation: 24169

I ran into this problem myself and found an undocumented feature that can help—the 'LimitMaxLegendEntries' property of Legend ('matlab.graphics.illustration.Legend') objects. Here's an example:

hF = figure(); 
hAx = axes(hF);
plot(hAx, magic(100));
hL = legend(hAx, '-DynamicLegend');
set(hL, 'LimitMaxLegendEntries', false, 'NumColumns', 3);

Which results in:

enter image description here

Tested on R2020a.

P.S.
While I agree that these likely way too many legend entries to be useful, I believe one should have the freedom to shoot themselves in the foot.

Upvotes: 3

Wolfie
Wolfie

Reputation: 30046

As implied by Cris's comment, it's likely that your plot is going to be very unclear - if you need 50+ legend entries then you've got 50+ different line styles, which is pretty crazy from a usability perspective.

That aside, you can achieve an unrestricted legend using the gridLegend FileExchange submission.

% Plot some dummy data, 60 series with various markers / lines
ms = {'*','+','.','d','s','o'};
ls = {'--','-',':','-.'};
x = linspace( 0, 10, 100 ).';
figure(); hold on;
for ii = 1:60;
    y = sin(x+ii) + ii + rand(100,1)/2;
    p(ii) = plot( x, y, ms{randi(6)}, 'linestyle', ls{randi(4)} );
end
% Call the legend
gridLegend( p );

Output:

plot

Upvotes: 3

Related Questions