fill area between two curves? fill_between?

John Hunter: Normally I wouldn't waste bandwith in a mailing-list by sending
neither a question nor an answer, but in this case I feel the urge to thank
you for your support. Your function does exactly what I need and you even
gave a hint on how to implement such functional extensions. On top of that,
the answer came an hour after I sent the question :slight_smile:

All of the matplotlib plot commands create primitive objects
(lines.Line2D, patches.Rectangle, patches.Polygon, text.Text). If a
plot command doesn't suit your needs, you can roll your own by
creating the right kind of primitive object. [...]

Do I have to dive into the class description at
http://matplotlib.sourceforge.net/classdocs.html to get this informations or
is there a more user-friendly description of the matplotlib internals?

Thanks
Dirk

···

----- Original Message -----
From: "John Hunter" <jdhunter@...4...>
To: <replytodirk@...273...>
Cc: <matplotlib-users@lists.sourceforge.net>
Sent: Tuesday, September 28, 2004 2:15 PM
Subject: Re: [Matplotlib-users] fill area between two curves? fill_between?

    > I want to fill the area between two curves with a color
    > (incl. alpha channel, I use the agg backend). fill() seems
    > to fill only the area between the x-axis and one curve - at
    > least I found no way for filling only the area between two
    > graphs. Is there a way for doing so at all? Or do I have to
    > use another graphic library for this kind of fill_between()?

All of the matplotlib plot commands create primitive objects
(lines.Line2D, patches.Rectangle, patches.Polygon, text.Text). If a
plot command doesn't suit your needs, you can roll your own by
creating the right kind of primitive object. Here is a fill_between
implementation

from matplotlib.matlab import *
from matplotlib.patches import Polygon

def fill_between(ax, x, y1, y2, **kwargs):
    # add x,y2 in reverse order for proper polygon filling
    verts = zip(x,y1) + [(x[i], y2[i]) for i in range(len(x)-1,-1,-1)]
    poly = Polygon(verts, **kwargs)
    ax.add_patch(poly)
    ax.autoscale_view()
    return poly

x = arange(0, 2, 0.01)
y1 = sin(2*pi*x)
y2 = sin(4*pi*x) + 2
ax = gca()

p = fill_between(ax, x, y1, y2, facecolor='g')
p.set_alpha(0.5)
show()

Hope this helps,
JDH