How to plot counties and shade them according with a specified color?
I forgot that this has been an old question for me.
Where to get county shape files?
A UScounty shapefile is included in basemap version 1.0.6. Unfortunately, the latest version of basemap provided by enpkg is 1.0.2 (and I've not successfully been able to compile from source on a Mac).
I think it's safe to copy the USCounties files over from version 1.0.6 to your basemap data directory, but I'd rather not add files to that directory.
Alternative: download files from US Census
http://www.census.gov/geo/www/tiger/tgrshp2012/tgrshp2012.html
ftp interface: ftp://ftp2.census.gov/geo/tiger/TIGER2012/COUNTY/ -> ftp://ftp2.census.gov/geo/tiger/TIGER2012/COUNTY/tl_2012_us_county.zip
I've not added these files to the working-open-data repo because I don't want large data files in the repo if possible.
import numpy as np
import matplotlib.pyplot as plt
with warnings.catch_warnings():
warnings.simplefilter("ignore")
from mpl_toolkits.basemap import Basemap
# you can figure out where the data directory for basemap is
import os
import inspect
basemap_data_dir = os.path.join(os.path.dirname(inspect.getfile(Basemap)), "data")
print basemap_data_dir, os.path.exists(os.path.join(basemap_data_dir,"UScounties.shp"))
/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/site-packages/mpl_toolkits/basemap/data False
!ls $basemap_data_dir
FL bmng.jpg epsg gshhsmeta_i.dat lsmask_10min_c.bin lsmask_2.5min_i.bin nad27 prvi states_c.dat stpaul GL27 conus esri gshhsmeta_l.dat lsmask_10min_f.bin lsmask_2.5min_l.bin nad83 rivers_c.dat states_i.dat td_out.dist MD countries_c.dat esri.extra hawaii lsmask_10min_h.bin lsmask_5min_c.bin ntv2_out.dist rivers_i.dat states_l.dat test27 README countries_i.dat etopo1.jpg lsmask_1.25min_c.bin lsmask_10min_i.bin lsmask_5min_f.bin null rivers_l.dat statesmeta_c.dat test83 TN countries_l.dat gshhs_c.dat lsmask_1.25min_f.bin lsmask_10min_l.bin lsmask_5min_h.bin other.extra riversmeta_c.dat statesmeta_i.dat testntv2 WI countriesmeta_c.dat gshhs_i.dat lsmask_1.25min_h.bin lsmask_2.5min_c.bin lsmask_5min_i.bin pj_out27.dist riversmeta_i.dat statesmeta_l.dat testvarious WO countriesmeta_i.dat gshhs_l.dat lsmask_1.25min_i.bin lsmask_2.5min_f.bin lsmask_5min_l.bin pj_out83.dist riversmeta_l.dat stgeorge world alaska countriesmeta_l.dat gshhsmeta_c.dat lsmask_1.25min_l.bin lsmask_2.5min_h.bin nad.lst proj_def.dat shadedrelief.jpg stlrnc
# https://code.google.com/p/pyshp/
import shapefile
# this is my git clone of https://github.com/matplotlib/basemap --> these files will be in the PiCloud basemap_data_dir
if os.path.exists(os.path.join(basemap_data_dir,"UScounties.shp")):
shpf = shapefile.Reader(os.path.join(basemap_data_dir,"UScounties"))
else:
# put in your path
#shpf = shapefile.Reader("/Users/raymondyee/Dropbox/WwoD13/tl_2012_us_county")
shpf = shapefile.Reader("/Users/raymondyee/C/src/basemap/lib/mpl_toolkits/basemap/data/UScounties")
shapes = shpf.shapes()
records = shpf.records()
shpf.fields
[('DeletionFlag', 'C', 1, 0), ['STATE_FIPS', 'C', 2, 0], ['COUNTY_FIP', 'C', 3, 0], ['FIPS', 'C', 5, 0], ['STATE', 'C', 2, 0], ['NAME', 'C', 25, 0], ['LSAD', 'C', 10, 0]]
zip([f[0] for f in shpf.fields[1:]], records[0])
[('STATE_FIPS', '01'), ('COUNTY_FIP', '029'), ('FIPS', '01029'), ('STATE', 'AL'), ('NAME', 'Cleburne'), ('LSAD', 'County')]
# just CA
from itertools import islice, izip
len([r for r in islice(records,None) if r[0] == '06'])
58
def zip_filter_by_state(records, shapes, included_states=None):
# by default, no filtering
# included_states is a list of states fips prefixes
for (record, state) in izip(records, shapes):
if record[0] in included_states:
yield (record, state)
list(zip_filter_by_state(records, shapes, ['06']))
[(['06', '035', '06035', 'CA', 'Lassen', 'County'], <shapefile._Shape instance at 0x26ca1e8>), (['06', '049', '06049', 'CA', 'Modoc', 'County'], <shapefile._Shape instance at 0x26ca238>), (['06', '075', '06075', 'CA', 'San Francisco', 'County'], <shapefile._Shape instance at 0x26ca288>), (['06', '083', '06083', 'CA', 'Santa Barbara', 'County'], <shapefile._Shape instance at 0x26ca2d8>), (['06', '091', '06091', 'CA', 'Sierra', 'County'], <shapefile._Shape instance at 0x26ca328>), (['06', '095', '06095', 'CA', 'Solano', 'County'], <shapefile._Shape instance at 0x26ca378>), (['06', '101', '06101', 'CA', 'Sutter', 'County'], <shapefile._Shape instance at 0x26ca3c8>), (['06', '105', '06105', 'CA', 'Trinity', 'County'], <shapefile._Shape instance at 0x4587788>), (['06', '111', '06111', 'CA', 'Ventura', 'County'], <shapefile._Shape instance at 0x45dd030>), (['06', '115', '06115', 'CA', 'Yuba', 'County'], <shapefile._Shape instance at 0x45ab7d8>), (['06', '033', '06033', 'CA', 'Lake', 'County'], <shapefile._Shape instance at 0x45ab620>), (['06', '071', '06071', 'CA', 'San Bernardino', 'County'], <shapefile._Shape instance at 0x45ab800>), (['06', '087', '06087', 'CA', 'Santa Cruz', 'County'], <shapefile._Shape instance at 0x45d4968>), (['06', '001', '06001', 'CA', 'Alameda', 'County'], <shapefile._Shape instance at 0x45d4d00>), (['06', '003', '06003', 'CA', 'Alpine', 'County'], <shapefile._Shape instance at 0x45d4d78>), (['06', '005', '06005', 'CA', 'Amador', 'County'], <shapefile._Shape instance at 0x45d4b98>), (['06', '007', '06007', 'CA', 'Butte', 'County'], <shapefile._Shape instance at 0x45d4e40>), (['06', '009', '06009', 'CA', 'Calaveras', 'County'], <shapefile._Shape instance at 0x45d4b48>), (['06', '011', '06011', 'CA', 'Colusa', 'County'], <shapefile._Shape instance at 0x45d4c10>), (['06', '013', '06013', 'CA', 'Contra Costa', 'County'], <shapefile._Shape instance at 0x45d4fd0>), (['06', '015', '06015', 'CA', 'Del Norte', 'County'], <shapefile._Shape instance at 0x45d4b20>), (['06', '017', '06017', 'CA', 'El Dorado', 'County'], <shapefile._Shape instance at 0x45e1b98>), (['06', '019', '06019', 'CA', 'Fresno', 'County'], <shapefile._Shape instance at 0x45e1f30>), (['06', '021', '06021', 'CA', 'Glenn', 'County'], <shapefile._Shape instance at 0x45e1620>), (['06', '023', '06023', 'CA', 'Humboldt', 'County'], <shapefile._Shape instance at 0x45e1cd8>), (['06', '025', '06025', 'CA', 'Imperial', 'County'], <shapefile._Shape instance at 0x45e1918>), (['06', '027', '06027', 'CA', 'Inyo', 'County'], <shapefile._Shape instance at 0x45e1df0>), (['06', '029', '06029', 'CA', 'Kern', 'County'], <shapefile._Shape instance at 0x45e18a0>), (['06', '031', '06031', 'CA', 'Kings', 'County'], <shapefile._Shape instance at 0x45e17d8>), (['06', '037', '06037', 'CA', 'Los Angeles', 'County'], <shapefile._Shape instance at 0x45e1968>), (['06', '039', '06039', 'CA', 'Madera', 'County'], <shapefile._Shape instance at 0x45e1b20>), (['06', '041', '06041', 'CA', 'Marin', 'County'], <shapefile._Shape instance at 0x45e1b70>), (['06', '043', '06043', 'CA', 'Mariposa', 'County'], <shapefile._Shape instance at 0x45e1698>), (['06', '045', '06045', 'CA', 'Mendocino', 'County'], <shapefile._Shape instance at 0x45e16c0>), (['06', '047', '06047', 'CA', 'Merced', 'County'], <shapefile._Shape instance at 0x45e16e8>), (['06', '051', '06051', 'CA', 'Mono', 'County'], <shapefile._Shape instance at 0x45e1ee0>), (['06', '053', '06053', 'CA', 'Monterey', 'County'], <shapefile._Shape instance at 0x45e1d00>), (['06', '055', '06055', 'CA', 'Napa', 'County'], <shapefile._Shape instance at 0x45e1508>), (['06', '057', '06057', 'CA', 'Nevada', 'County'], <shapefile._Shape instance at 0x45e1af8>), (['06', '059', '06059', 'CA', 'Orange', 'County'], <shapefile._Shape instance at 0x45e1c60>), (['06', '061', '06061', 'CA', 'Placer', 'County'], <shapefile._Shape instance at 0x45e1f80>), (['06', '063', '06063', 'CA', 'Plumas', 'County'], <shapefile._Shape instance at 0x45e1aa8>), (['06', '065', '06065', 'CA', 'Riverside', 'County'], <shapefile._Shape instance at 0x45e1da0>), (['06', '067', '06067', 'CA', 'Sacramento', 'County'], <shapefile._Shape instance at 0x45e13c8>), (['06', '069', '06069', 'CA', 'San Benito', 'County'], <shapefile._Shape instance at 0x45e1d28>), (['06', '073', '06073', 'CA', 'San Diego', 'County'], <shapefile._Shape instance at 0x45e1788>), (['06', '077', '06077', 'CA', 'San Joaquin', 'County'], <shapefile._Shape instance at 0x45eb530>), (['06', '079', '06079', 'CA', 'San Luis Obispo', 'County'], <shapefile._Shape instance at 0x45eb580>), (['06', '081', '06081', 'CA', 'San Mateo', 'County'], <shapefile._Shape instance at 0x45eb2b0>), (['06', '085', '06085', 'CA', 'Santa Clara', 'County'], <shapefile._Shape instance at 0x45eb0a8>), (['06', '089', '06089', 'CA', 'Shasta', 'County'], <shapefile._Shape instance at 0x45eb328>), (['06', '093', '06093', 'CA', 'Siskiyou', 'County'], <shapefile._Shape instance at 0x45eb080>), (['06', '097', '06097', 'CA', 'Sonoma', 'County'], <shapefile._Shape instance at 0x45eb378>), (['06', '099', '06099', 'CA', 'Stanislaus', 'County'], <shapefile._Shape instance at 0x45eb4e0>), (['06', '103', '06103', 'CA', 'Tehama', 'County'], <shapefile._Shape instance at 0x45eb288>), (['06', '107', '06107', 'CA', 'Tulare', 'County'], <shapefile._Shape instance at 0x45eb058>), (['06', '109', '06109', 'CA', 'Tuolumne', 'County'], <shapefile._Shape instance at 0x45e2918>), (['06', '113', '06113', 'CA', 'Yolo', 'County'], <shapefile._Shape instance at 0x45e2198>)]
len(shapes)
3221
# http://www.geophysique.be/2013/02/12/matplotlib-basemap-tutorial-10-shapefiles-unleached-continued/
#
# BaseMap example by geophysique.be
# tutorial 10
import os
import inspect
import numpy as np
import matplotlib.pyplot as plt
from itertools import islice, izip
from mpl_toolkits.basemap import Basemap
### PARAMETERS FOR MATPLOTLIB :
import matplotlib as mpl
mpl.rcParams['font.size'] = 10.
mpl.rcParams['font.family'] = 'Comic Sans MS'
mpl.rcParams['axes.labelsize'] = 8.
mpl.rcParams['xtick.labelsize'] = 6.
mpl.rcParams['ytick.labelsize'] = 6.
fig = plt.figure(figsize=(11.7,8.3))
#Custom adjust of the subplots
plt.subplots_adjust(left=0.05,right=0.95,top=0.90,bottom=0.05,wspace=0.15,hspace=0.05)
ax = plt.subplot(111)
#Let's create a basemap of USA
x1 = -180.
x2 = -62.
y1 = 18.
y2 = 68.
m = Basemap(resolution='i',projection='merc', llcrnrlat=y1,urcrnrlat=y2,llcrnrlon=x1,urcrnrlon=x2,lat_ts=(y1+y2)/2)
m.drawcountries(linewidth=0.5)
m.drawcoastlines(linewidth=0.5)
m.drawparallels(np.arange(y1,y2,2.),labels=[1,0,0,0],color='black',dashes=[1,0],labelstyle='+/-',linewidth=0.2) # draw parallels
m.drawmeridians(np.arange(x1,x2,2.),labels=[0,0,0,1],color='black',dashes=[1,0],labelstyle='+/-',linewidth=0.2) # draw meridians
def zip_filter_by_state(records, shapes, included_states=None):
# by default, no filtering
# included_states is a list of states fips prefixes
for (record, state) in izip(records, shapes):
if record[0] in included_states:
yield (record, state)
from matplotlib.collections import LineCollection
from matplotlib import cm
import shapefile
basemap_data_dir = os.path.join(os.path.dirname(inspect.getfile(Basemap)), "data")
# this is my git clone of https://github.com/matplotlib/basemap --> these files will be in the PiCloud basemap_data_dir
if os.path.exists(os.path.join(basemap_data_dir,"UScounties.shp")):
shpf = shapefile.Reader(os.path.join(basemap_data_dir,"UScounties"))
else:
# put in your path
#shpf = shapefile.Reader("/Users/raymondyee/Dropbox/WwoD13/tl_2012_us_county")
shpf = shapefile.Reader("/Users/raymondyee/C/src/basemap/lib/mpl_toolkits/basemap/data/UScounties")
shapes = shpf.shapes()
records = shpf.records()
# show only CA and AK (for example)
for record, shape in zip_filter_by_state(records, shapes, ['06', '02']):
lons,lats = zip(*shape.points)
data = np.array(m(lons, lats)).T
if len(shape.parts) == 1:
segs = [data,]
else:
segs = []
for i in range(1,len(shape.parts)):
index = shape.parts[i-1]
index2 = shape.parts[i]
segs.append(data[index:index2])
segs.append(data[index2:])
lines = LineCollection(segs,antialiaseds=(1,))
lines.set_facecolors(cm.jet(np.random.rand(1)))
lines.set_edgecolors('k')
lines.set_linewidth(0.1)
ax.add_collection(lines)
plt.savefig('tutorial10.png',dpi=300)
plt.show()