Alex
Alex

Reputation: 319

MatLab: optional turn on legend

I'm trying to write the code to set up the figures and legend to look nice. I made code that plotting the figures

figure(1)
hold on
plot(x1, y1, 'DisplayName', name1)
plot(x2, y2, 'DisplayName', name2)
plot(x3, y3, 'DisplayName', name3)

Now, I need another script, that should turn the legend on only if name1 name2 and name3 in original figure were actually set to some non-default value i.e. not '', otherwise I don't need a legend at all.

function optionallegend(figure)
if ????
     legend('show');
end

Can I do that?

Upvotes: 2

Views: 172

Answers (1)

Suever
Suever

Reputation: 65430

You can use findobj to locate all plot objects within your current axes that have the DisplayName property and have defined it to be something other than ''. findobj returns an array of handles which can then be passed to legend. If no plots meet that criteria, then no legend will be shown.

plots = findobj(gca, '-not', 'DisplayName', '', '-property', 'DisplayName');

if ~isempty(plots); legend(plots); end

And as an example

figure;
hax = axes();
hold(hax, 'on')

plot(rand(5,1), 'DisplayName', 'Plot #1');
plot(rand(5,1))
plot(rand(5,1), 'DisplayName', 'Plot #3');

legend(findobj(hax, '-not', 'DisplayName', '', '-property', 'DisplayName'));

enter image description here

If instead you want to simply plot a legend for only specific plots, you can explicitly store the plot handles and pass those to legend directly.

hplot1 = plot(rand(5,1), 'DisplayName', 'Plot #1');
hplot2 = plot(rand(5,1), 'DisplayName', 'Plot #2');

legend([hplot1, hplot2])

Upvotes: 3

Related Questions