title: How to clip contours inside of shape file using matplotlib?
body: <p>I'm doing a kernel density plot but my contours are extending out into areas of water. I don't have much experience with coding, but I used a shape file to plot my "base map". However, I'm not sure how to go about creating a clip path from my shape file so that the contours are cut against the edges of the country. Any guidance on this issue would be really appreciated.</p>
  
  <p>I decided to create a clip path using the outer boundaries of my shapefile.
  However, when I applied the set_clip_path function to my contour collections, the inside of the polygon boundaries was clipped instead.
  Here is the gist of the code I used.</p>
  
  <pre><code>import pandas as pd
  import numpy as np
  import matplotlib.pyplot as plt
  import matplotlib.path as mpath
  import matplotlib.patches as mpatches
  import shapefile as shp
  
  lon_lat_box = (-61.979370, -60.444031, 9.974261, 11.375031)
  
  fig = plt.figure(figsize=(15,15))
  ax1 = fig.add_subplot(1,1,1)
  
  Path = mpath.Path
  
  #read shape file
  sfile = shp.Reader("./tto_adm0/TTO_adm0.shp")
  
  #make clip path
  for shape_rec in sfile.shapeRecords():
      vertices = []
      codes = []
      pts = shape_rec.shape.points
      prt = list(shape_rec.shape.parts) + [len(pts)]
      for i in range(len(prt) - 1):
          for j in range(prt[i], prt[i+1]):
              vertices.append((pts[j][0], pts[j][1]))
          codes += [Path.MOVETO]
          codes += [Path.LINETO] * (prt[i+1] - prt[i] -2)
          codes += [Path.CLOSEPOLY]
      clip = mpath.Path(vertices, codes)
      clip = mpatches.PathPatch(clip, facecolor = 'white')
  
  #plot    
  ax1.add_patch(clip)
  plt.xlim(lon_lat_box[0],lon_lat_box[1])
  plt.ylim(lon_lat_box[2],lon_lat_box[3])
  
  plot_map(shape_ex)
  ax1.contourf(xx, yy, Z, cut, cmap="jet", alpha=0.3)
  contour = ax1.contourf(xx, yy, Z, cut, cmap="jet", alpha=0.3)
  C = plt.contourf(xx, yy, Z, cut, cmap="jet", alpha=0.3)
  plt.colorbar(C)
  for c in contour.collections:
      c.set_clip_path(clip)    
  
  fig.savefig(pdf_name)
  fig.show()
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/xEW4p.png" rel="nofollow noreferrer">Here is what the output looks like right now</a></p>
  
  <p>Update:
  I realized that the line "ax1.add_patch(clip)" just masks all of the contour fill inside of the country boundaries, since I set the face color to white. 
  This means that the contours are still not being clipped using my patch created, and I don't know why. </p>
  
  <p>The result if I removed the "ax1.add_patch(clip)" line looks like <a href="https://i.stack.imgur.com/iQBco.png" rel="nofollow noreferrer">this</a></p>
  
  <p>Update 2:
  With  ImportanceOfBeingErnest's suggestion, I was able to resolve my issue and obtain <a href="https://i.stack.imgur.com/5xqUX.png" rel="nofollow noreferrer">the desired output</a>
  The following adjustments to my code were made: </p>
  
  <pre><code>contour = ax1.contourf(xx, yy, Z, cut, cmap="jet", alpha=0.3)
  plt.colorbar(contour)
  for c in contour.collections:
  c.set_clip_path(clip)   
  </code></pre>