# MATLAB – Ignoring Plots in a Legend Plotting in MATLAB can be interesting. Whichever you choose to plot first will end up at the back of the figure with all the plots that come after on top of it. Because of this, I like to put patch plots in the back (the red and blue between the black outline) and then plot the outlines after. The result is what you see above.

Here’s what the code looks like to make the above figure:

close all
clear
clc

n = 0:0.01:10;
x1 = n.^3 / 100 + sin(2*pi*n);
x2 = n - 1.5;

...

a1 = patch(...);
a2 = patch(...);

p1 = plot(n, x1, 'k-', 'linewidth', 3);
p2 = plot(n, x2, 'k--', 'linewidth', 3);

(I intentionally simplified the patch code because the actual code to plot the red and blue fills gets confusing. See snipIndex if you’re interested.)

The problem with plotting the patch plots first is that if you want to make a legend, then the patch plots are going to be labeled first. If I just made a legend of the two outline functions, you can see the result below. Unfortunately, in MATLAB, ignoring plots in a legend isn’t really intuitive. To do it, you’ll have to use code that looks similar to this:

close all
clear
clc

n = 0:0.01:10;
x1 = n.^3 / 100 + sin(2*pi*n);
x2 = n - 1.5;

...

a1 = patch(...);
a2 = patch(...);

% These next two lines turn off a1 and a2 from the legend, very important!!
set(get(get(a1, 'Annotation'), 'LegendInformation'), ...
'IconDisplayStyle', 'off')
set(get(get(a2, 'Annotation'), 'LegendInformation'), ...
'IconDisplayStyle', 'off')

p1 = plot(n, x1, 'k-', 'linewidth', 3);
p2 = plot(n, x2, 'k--', 'linewidth', 3);
legend('x1(n) = n^3/100 + sin(2*\pi*n)', 'x2(n) = n - 1.5', ...
'Location', 'North') Those two new lines removed the two patch plots from the legend. As you can see, it’s not really intuitive, but at least we have the correct legend entries!

## 3 thoughts on “MATLAB – Ignoring Plots in a Legend”

1. Francis says:

Thanks so much, really helped me out

2. Sören G. says:

Well, that seems to be a quite “elaborate” workaround. Why don’t you just issue the “legend([p1,p2],{‘Text1’,’Text2})” command, as the help tells me to?! I’m pretty sure that worked back in the old days of 2010, at least for me… or did I dramatically misunderstand something here?

1. Bryant says:

That’s a good question… Looking back through the Matlab documentation I believe I based this post on this article in the Matlab documentation.

I’ll definitely be passing handles from now on though. Thanks for your comment!