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 comments

Comments feed for this article

7 September 2011 at 16:23

FrancisThanks so much, really helped me out

28 December 2011 at 14:31

Sören G.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?

28 December 2011 at 14:43

BryantThat’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!