Skip to content

Instantly share code, notes, and snippets.

@shaneshifflett
Created February 5, 2013 19:14
Show Gist options
  • Save shaneshifflett/4716832 to your computer and use it in GitHub Desktop.
Save shaneshifflett/4716832 to your computer and use it in GitHub Desktop.
Dead simple Dot Density plotter. Will create a point for every item in a CSV file that intersects a shapefile given a column to match with a geography's name.
from django.contrib.gis.geos import Point
from django.contrib.gis.gdal import DataSource
import random
import csv
def dotdensity(shape_id_key=None, col_id_key=None,\
shapefilepath=None, datafilepath=None, outputfilepath=None, filter_map=None):
reader = list(csv.reader(open(datafilepath, 'rb')))
header = reader[0]
rows = reader[1:]
if filter_map is not None:
for key in filter_map.keys():
idx = header.index(key)
rows = filter(lambda row: filter_map[key](row, idx), rows)
writer = csv.writer(open(outputfilepath, 'wb'), delimiter=',')
header = reader[0] + ['longitude', 'latitude']
ds = DataSource(shapefilepath)[0]
shapes = dict([[obj.get(shape_id_key), obj.geom] for obj in ds])
writer.writerow(header)
unmatched = 0
for idx, row in enumerate(rows):
try:
code = header.index(col_id_key)
geo = shapes[row[code]]
gotcha = False
while not gotcha:
minx, miny, maxx, maxy = geo.extent
x = random.uniform(minx,maxx)
y = random.uniform(miny,maxy)
point = Point(x,y,srid=geo.srid)
if point.intersects(geo.geos):
print 'writing %s' % idx
writer.writerow(row + [x, y])
gotcha = True
except KeyError:
unmatched += 1
print 'total=%s matched=%s unmatched=%s' % (len(rows), len(rows) - unmatched, unmatched)
filter_func = {'CASUALTY COUNTRY': lambda row, idx: row[idx] != 'US'}
'''
dotdensity('wb_a2', 'CASUALTY COUNTRY',\
'data/natural_earth_vector/10m_cultural/ne_10m_admin_0_countries.shp',\
'data/suicide_vets.csv', 'data/latlng_output.csv', filter_func)
'''
filter_func = {'CASUALTY COUNTRY': lambda row, idx: row[idx] == 'US'}
dotdensity('STUSPS10', 'CASUALTY STATE',\
'data/State_2010Census_DP1/State_2010Census_DP1.shp',\
'data/suicide_vets.csv', 'data/state_latlng_output.csv', filter_func)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment