1

For the code below, besides having the relevant modules installed, you will need to download and unpack the file "nationp010g.shp.tar.gz" that can be found here. This file is a shape file of the United States. If anyone has a better way of displaying these boundaries, by all means suggest it!

For my test case below, I have succeeded in colouring in the united states blue. What I want to do is to plot contour plots as if only the land portions of the USA are allowed. Im not sure how this can be accomplished without using a tedious for loop which loops through all the coordinates and checks whether the coordinate in question is inside the polygon given by the shape file. What is the best way to accomplish what I want? Here is the result:

enter image description here

from __future__ import print_function


import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap as Basemap
from matplotlib.colors import rgb2hex
from matplotlib.patches import Polygon

m = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
            projection='lcc',lat_1=33,lat_2=45,lon_0=-95)

shp_info = m.readshapefile('nationp010g/nationp010g', 'borders', drawbounds=True) 


print(dir(m)) #List all attributes of an object
ax = plt.gca()
color = 'blue'
for nshape,seg in enumerate(m.borders):
    poly = Polygon(seg,facecolor=color,edgecolor=color)
    ax.add_patch(poly)

xmax, ymax = m(m.lonmax, m.latmax )
xmin, ymin = m(m.lonmin, m.latmin)

y = np.linspace(ymin,ymax,100)
x = np.linspace(xmin, xmax, 100)
X, Y = np.meshgrid(x, y)
Z = (X-(xmax-xmin)/2)**2+(Y-(ymax-ymin)/2)**2

ax.contour(X,Y, Z, cmap=plt.get_cmap('coolwarm'))
plt.show()
Dipole
  • 1,840
  • 2
  • 24
  • 35
  • 1
    the contouring function should return a list of `Line2D` artists. those artists should have a method along the lines of `set_clip_path`. Pretty sure you can set that to the artist of the shapefile. Something like that. – Paul H Sep 05 '14 at 16:45
  • I played around with this idea, but I encountered some problems, I created a new question for this more specific issue found at: http://stackoverflow.com/questions/25701321/how-to-use-set-clipped-path-for-basemap-polygon?noredirect=1#comment40177120_25701321 – Dipole Sep 06 '14 at 22:07

0 Answers0