13

I use plot(x,y,'r') to plot a red circle. x and y are arrays such that when paired as (x,y) and plotted, all points form a circle-line.

fill(x,y,'r') plots a red circle that is filled in (or colored in) red.

How can I keep the circle white on the inside, but fill outside the circle out to the axis boundaries?

I looked into using fill_between(x_array, y1_array, y2_array, where) but after a little playing with it I don’t think that will work for my x,y arrays. I thought to fill_between() outside the circle, and inside a square that is defined by the axis boundaries, but I don’t think fill_between() is capable… I’m sure I could make it into an integral type of problem with delta x and delta y going to zero, but I’m not willing to.

If anyone can see that I’m missing something with fill_between() please let me know.

All I am really needing to do is mask out numbers in a 2d array that are located beyond this boundary of the circle created with x and y, such that when the 2D array is viewed as a color plot, or contour, inside the circle will be the image, and outside will be white-ed out.

Can this be accomplished by a masking technique of the 2D array instead? Like by using masked_where() ? I haven’t looked into it yet, but will.

Any ideas? Thanks

Edit 1: Here is what i have permission to show that I think will explain my problem.

from pylab import *
from matplotlib.path import Path
from matplotlib.patches import PathPatch

f=Figure()
a=f.add_subplot(111)

# x,y,z are 2d arrays

# sometimes i plot a color plot
# im = a.pcolor(x,y,z)
a.pcolor(x,y,z)

# sometimes i plot a contour
a.contour(x,y,z)

# sometimes i plot both using a.hold(True)

# here is the masking part.
# sometimes i just want to see the boundary drawn without masking
# sometimes i want to see the boundary drawn with masking inside of the boundary
# sometimes i want to see the boundary drawn with masking outside of the boundary

# depending on the vectors that define x_bound and y_bound, sometimes the boundary
# is a circle, sometimes it is not.

path=Path(vpath)
patch=PathPatch(path,facecolor='none')
a.add_patch(patch) # just plots boundary if anything has been previously plotted on a
if ('I want to mask inside'):
    patch.set_facecolor('white') # masks(whitens) inside if pcolor is currently on a,
    # but if contour is on a, the contour part is not whitened out. 
else: # i want to mask outside 
    im.set_clip_path(patch) # masks outside only when im = a.pcolor(x,y,z)
    # the following commands don't update any masking but they don't produce errors?
    # patch.set_clip_on(True)
    # a.set_clip_on(True)
    # a.set_clip_path(patch)

a.show()

3 Answers 3

16

All I am really needing to do is mask out numbers in a 2d array that are located beyond this boundary of the circle created with x and y, such that when the 2D array is viewed as a color plot, or contour, inside the circle will be the image, and outside will be white-ed out.

You have two options:

First, you could use a masked array for the images. This is more complicated but a bit more failsafe. To mask an array outside of a circle, generate a distance map from the center point, and mask where distance is greater than the radius.

The easier option is to clip the areas ouside of the patch with im.set_clip_path() after you've plotted the image.

See this example from the matplotlib gallery. Unfortunately, with some axes (non-cartesian axes) this can be a bit glitchy, in my experience. In every other case it should work perfectly, though.

Edit: Incidentally, this is how to do what you originally asked: plot a polygon with a hole inside. If you just want to mask an image, though, you're better off with either of the two options above.

Edit2: Just to give a quick example of both ways...

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

def main():
    # Generate some random data
    nx, ny = 100, 100
    data = np.random.random((ny,nx))

    # Define a circle in the center of the data with a radius of 20 pixels
    radius = 20
    center_x = nx // 2
    center_y = ny // 2

    plot_masked(data, center_x, center_y, radius)
    plot_clipped(data, center_x, center_y, radius)
    plt.show()

def plot_masked(data, center_x, center_y, radius):
    """Plots the image masked outside of a circle using masked arrays"""
    # Calculate the distance from the center of the circle
    ny, nx = data.shape
    ix, iy = np.meshgrid(np.arange(nx), np.arange(ny))
    distance = np.sqrt((ix - center_x)**2 + (iy - center_y)**2)

    # Mask portions of the data array outside of the circle
    data = np.ma.masked_where(distance > radius, data)

    # Plot
    plt.figure()
    plt.imshow(data)
    plt.title('Masked Array')

def plot_clipped(data, center_x, center_y, radius):
    """Plots the image clipped outside of a circle by using a clip path"""
    fig = plt.figure()
    ax = fig.add_subplot(111)

    # Make a circle
    circ = patches.Circle((center_x, center_y), radius, facecolor='none')
    ax.add_patch(circ) # Plot the outline

    # Plot the clipped image
    im = ax.imshow(data, clip_path=circ, clip_on=True)

    plt.title('Clipped Array')

main()

enter image description here enter image description here

Edit 2: Plotting a mask polygon over the original plot: Here's a bit more detail on how to plot a polygon that masks everything outside of it over the current plot. Apparently, there isn't a better way to clip contour plots (That I could find, anyway...).

import numpy as np
import matplotlib.pyplot as plt

def main():
    # Contour some regular (fake) data
    grid = np.arange(100).reshape((10,10))
    plt.contourf(grid)

    # Verticies of the clipping polygon in counter-clockwise order
    #  (A triange, in this case)
    poly_verts = [(2, 2), (5, 2.5), (6, 8), (2, 2)]

    mask_outside_polygon(poly_verts)

    plt.show()

def mask_outside_polygon(poly_verts, ax=None):
    """
    Plots a mask on the specified axis ("ax", defaults to plt.gca()) such that
    all areas outside of the polygon specified by "poly_verts" are masked.  

    "poly_verts" must be a list of tuples of the verticies in the polygon in
    counter-clockwise order.

    Returns the matplotlib.patches.PathPatch instance plotted on the figure.
    """
    import matplotlib.patches as mpatches
    import matplotlib.path as mpath

    if ax is None:
        ax = plt.gca()

    # Get current plot limits
    xlim = ax.get_xlim()
    ylim = ax.get_ylim()

    # Verticies of the plot boundaries in clockwise order
    bound_verts = [(xlim[0], ylim[0]), (xlim[0], ylim[1]), 
                   (xlim[1], ylim[1]), (xlim[1], ylim[0]), 
                   (xlim[0], ylim[0])]

    # A series of codes (1 and 2) to tell matplotlib whether to draw a line or 
    # move the "pen" (So that there's no connecting line)
    bound_codes = [mpath.Path.MOVETO] + (len(bound_verts) - 1) * [mpath.Path.LINETO]
    poly_codes = [mpath.Path.MOVETO] + (len(poly_verts) - 1) * [mpath.Path.LINETO]

    # Plot the masking patch
    path = mpath.Path(bound_verts + poly_verts, bound_codes + poly_codes)
    patch = mpatches.PathPatch(path, facecolor='white', edgecolor='none')
    patch = ax.add_patch(patch)

    # Reset the plot limits to their original extents
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

    return patch

if __name__ == '__main__':
    main()

Clipped contour plot

8
  • Thanks Joe. the set_clip_path does seem like my best option, but if i wanted to go with the first option, would I use MaskedArray() method?
    – AmyS
    Jul 23, 2010 at 19:13
  • @AmyS - Yep, I added an example to show both ways of doing things. Hope it helps! Jul 23, 2010 at 20:43
  • Thanks for the extras Joe. Intersting and helpful, but for the current app i am working on, my boundary is defined by two vectors that when paired sometimes form a circle, sometimes do not. I use pcolor() because my axis is defined by 2 2d arrays that are not always cartesian, and i cant figure out how to handle that with imshow(). Fortunately, set_clip_plath(patch) is an attr. for pcolor(), but not for contour() or plot() :( If you're are still interested, would you take a look at Edit 1 above of my question and see if I can add masking patch to axis without predefined pcolor?
    – AmyS
    Jul 27, 2010 at 0:15
  • @AmyS - See the added code snippet. It should plot a polygon filled everywhere outside of the defined polygon over the current plot. I thought there was a cleaner way to clip contours, but apparently there isn't. Hopefully this works a bit better! Jul 27, 2010 at 17:44
  • @JoeKington I realise this is an old post, but I just found it and had to thank you for such a tremendously useful code snippet! Just wish this question and answer were easier to find... I spent a while looking for solutions before I found yours.
    – Gabriel
    Jul 10, 2014 at 15:47
2

Note: This answer uses MATLAB syntax, since the question was originally tagged as such. However, even if you're using matplotlib in Python the concept should be the same even if the syntax is slightly different.

One option you have is to make a polygon that appears to have a hole in it, but really just has two of its edges wrapping around an empty space and touching. You can do this by creating a set of x and y coordinates that track around the edge of the circle, then track from the circle edge to the edge of a bounding square, then track around the edge of that square and back to the circle edge along the same line. Here's an example with a unit circle and a 4 by 4 square centered at the origin:

theta = linspace(0,2*pi,100);      %# A vector of 100 angles from 0 to 2*pi
xCircle = cos(theta);              %# x coordinates for circle
yCircle = sin(theta);              %# y coordinates for circle
xSquare = [2 2 -2 -2 2 2];         %# x coordinates for square
ySquare = [0 -2 -2 2 2 0];         %# y coordinates for square
hp = fill([xCircle xSquare],...    %# Plot the filled polygon
          [yCircle ySquare],'r');
axis equal                         %# Make axes tick marks equal in size

And here is the figure you should see:

alt text

Notice the line on the right joining the edges of the circle and square. This is where two edges of the red polygon meet and touch each other. If you don't want the edge lines to be visible, you can change their color to be the same as the fill color for the polygon like so:

set(hp,'EdgeColor','r');
2
  • Surely MATLAB has a way to plot polygons with holes directly?? Then again, I can't seem to find it either... Here's how matplotlib handles it: matplotlib.sourceforge.net/examples/api/donut_demo.html Jul 23, 2010 at 18:07
  • Thanks for the ideas guys. It seems the most convenient way is to make a patch from the path.Path class and work from there as in above example, or example given in other answer using set_clip_path()
    – AmyS
    Jul 23, 2010 at 19:08
2

Since this is the first result that comes up when googling matplotlib fill outside, I'll answer what has been proposed in the title.

Background

From what I understand matplotlib does not provide a function to fill the area outside a polygon, but only inside it with Axes.fill. If we create a bigger "outside" polygon that contains the smaller one, and join the two in a matter that does not create any intersections, it's possible to "fool" matplotlib into thinking the inside polygon is a crevice of the outside polygon. If the outside polygon is kept outside the view limits, then this will have the effect of filling the entire space outside the inner polygon.

polygon setup

One thing to keep in mind is the orientation of the outside polygon, because the channel connecting to the outside should not intersect itself. For this the orientation of the outer poly should be the opposite of the inner poly.

self intersecting path

Solution

The following function finds the points of the inner poly closest to the lower left corner and inserts there the path for the outer poly, taking care of the orientation using the signed area of the parallelogram created by the vectors for the splice point and the next one.

import numpy as np

def concat(*arrs) -> np.ndarray:
    return np.concatenate(tuple(map(np.asarray, arrs)))

def insert_at(outer_arr, arr, n) -> np.ndarray:
    outer_arr = np.asarray(outer_arr)
    prev, post = np.split(outer_arr, (n,))
    return concat(prev, arr, post)

def cross2d(x1, y1, x2, y2):
    return x1*y2-x2*y1

def is_clockwise(x1, y1, x2, y2):
    cp = cross2d(x1, y1, x2, y2)
    return cp < 0 if cp != 0 else None

def fill_outside(x, y, ll, ur, counter_clockwise=None):
    """
    Creates a polygon where x and y form a crevice of an outer
    rectangle with lower left and upper right corners `ll` and `ur`
    respectively. If `counter_clockwise` is `None` then the orientation
    of the outer polygon will be guessed to be the opposite of the
    inner connecting points.
    """
    x = np.asarray(x)
    y = np.asarray(y)
    xmin, ymin = ll
    xmax, ymax = ur
    xmin, ymin = min(xmin, min(x)), min(ymin, min(y))
    xmax, ymax = max(xmax, max(x)), max(ymax, max(y))
    corners = np.array([
        [xmin, ymin],
        [xmin, ymax],
        [xmax, ymax],
        [xmax, ymin],
        [xmin, ymin],
    ])
    lower_left = corners[0]
    # Get closest point to splicing corner
    x_off, y_off = x-lower_left[0], y-lower_left[1]
    closest_n = (x_off**2+y_off**2).argmin()
    # Guess orientation
    p = [x_off[closest_n], y_off[closest_n]]
    try:
        pn = [x_off[closest_n+1], y_off[closest_n+1]]
    except IndexError:
        # wrap around if we're at the end of the array
        pn = [x_off[0], y_off[0]]
    if counter_clockwise is None:
        counter_clockwise = not is_clockwise(*p, *pn)
    corners = corners[::-1] if counter_clockwise else corners
    # Join the arrays
    corners = concat(np.array([[x[closest_n], y[closest_n]]]), corners)
    xs, ys = np.transpose(corners)
    return insert_at(x, xs, closest_n), insert_at(y, ys, closest_n)

Examples

Filling outside a simple triangle

import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.set_figwidth(10)

x = [0, 1, 2]
y = [0, 1, 0]
ll, ur = (-.5, -.25), (2.5, 1.25)
x, y = fill_outside(x, y, ll, ur)
ax1.fill(x, y)
ax1.plot(x, y, c="C1")
ax2.fill(x, y)
ax2.set_xlim((ll[0], ur[0]))
ax2.set_ylim((ll[1], ur[1]))

Produces:

outside of triangle filled

Filling outside an arbitrary shape

import numpy as np

def concat(*arrs) -> np.ndarray:
    return np.concatenate(tuple(map(np.asarray, arrs)))

def z_eq_damping(damping, n=100):
    theta = np.arccos(damping)
    u = np.cos(theta)-np.sin(theta)*1j
    x = np.linspace(0, np.pi/u.imag, num=n)
    contour = np.exp(u*x)
    re, im = contour.real, contour.imag
    return concat(re, np.flip(re)), concat(im, np.flip(-im))

fig, (ax1, ax2) = plt.subplots(1, 2)
fig.set_figwidth(10)

x, y = z_eq_damping(.7)
ll, ur = (-1, -1), (1, 1)
x, y = fill_outside(x, y, ll, ur)
ax1.fill(x, y)
ax1.plot(x, y, c="C1")
ax2.fill(x, y)
ax2.set_xlim((ll[0], ur[0]))
ax2.set_ylim((ll[1], ur[1]))

Produces:

filled outside of shape

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.