whisp3r
whisp3r

Reputation: 21

python - plotting a polygon that masks everything outside of it over the current plot

I try to fill area outside the polygon, similar to the case explained in this topic: Fill OUTSIDE of polygon | Mask array where indicies are beyond a circular boundary?. Unfortunately, something in my case goes wrong. I am able to perform filling for some basic polygon, with few corners but when I try to do this for my target figure the whole plot is getting filled, instead of just its outside. Are there any limitations for filling patches or am I doing something wrong? Here is the exemplary code that I am working with.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches


xg, yg = np.mgrid[ax.min():ax.max():100j, ay.min():ay.max():100j]
rbf1 = Rbf(ax, ay, az, function='linear')
za = rbf1(xg, yg)
plt.contourf(xg, yg, za)

#some exemplary working polygon
#poly_verts = [[0.0432, -0.04234], [0.06542, -0.032345], [0.055423, -0.022345], [0.0355423, -0.01], [0.035234523, -0.0323452354], [0.0432, -0.04234]]

#data that is not working
poly_verts = ins_path
ax_s = plt.gca()
xlim = ax_s.get_xlim()
ylim = ax_s.get_ylim()

bound_verts = [(xlim[0], ylim[0]), (xlim[0], ylim[1]), (xlim[1], ylim[1]), (xlim[1], ylim[0]), (xlim[0], ylim[0])]
bound_codes = [mpath.Path.MOVETO] + (len(bound_verts) - 1) * [mpath.Path.LINETO]
poly_codes = [mpath.Path.MOVETO] + (len(poly_verts) - 1) * [mpath.Path.LINETO]
path = mpath.Path(bound_verts + poly_verts, bound_codes + poly_codes)
patch = mpatches.PathPatch(path, facecolor='white')
patch = ax_s.add_patch(patch)
ax_s.set_xlim(xlim)
ax_s.set_ylim(ylim)
plt.show()

and here is some exemplary data that I use for it: exemplary data

Thanks in advance for any suggestions.

Upvotes: 1

Views: 1054

Answers (1)

whisp3r
whisp3r

Reputation: 21

Hello it took me some time, but an answer came to me:). I am not sure it is not against rules but I think that answer may be useful to someone so I decided to share it. The problem was with my path direction, if you reverse it like this:

poly_verts = ins_path[::-1]

The code works perfect. It seems that direction of boundaries need to be the same otherwise filling is performed over the whole area(probably paths are mixing).

Upvotes: 1

Related Questions