-
Notifications
You must be signed in to change notification settings - Fork 0
/
choroplethmap.py
89 lines (61 loc) · 2.42 KB
/
choroplethmap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# Code adapted from:
# http://flowingdata.com/2009/11/12/how-to-make-a-us-county-thematic-map-using-free-tools/
import os
import csv
from BeautifulSoup import BeautifulSoup
from collections import OrderedDict
class ColorStateMap():
def __init__(self, colorDict, data, oFile):
self.colorDict = colorDict
self.data = data
self.oFile = oFile
mapFile = os.path.dirname(__file__) + '\\maps\\Blank_US_Map.svg'
blankMap = self.readFile(mapFile)
self.coloredMap = self.colorizeMap(blankMap, self.colorDict, self.data)
self.writeFile(self.oFile, self.coloredMap)
def readFile(self, filename):
with open(filename, 'r') as f:
contents = f.read()
return contents
def setStyleAttrib(self, cDict, p, value):
styleAttrib = 'font-size:12px;fill-rule:nonzero;stroke:#000000;' \
'stroke-opacity:1;stroke-width:0.4;stroke-miterlimit:4;' \
'stroke-dasharray:none;stroke-linecap:butt;marker-start:none;' \
'stroke-linejoin:bevel'
try:
for c, t in cDict.iteritems():
if value > t:
p['style'] = styleAttrib + ';fill:' + c
return p['style']
except:
pass
def colorizeMap(self, map, colorDict, data):
soup = BeautifulSoup(map, selfClosingTags=['defs',
'sodipodi:namedview'])
paths = soup.findAll('path')
for path in paths:
state = path['id']
if state in data:
self.setStyleAttrib(colorDict, path, data[path['id']])
elif (state == 'MI-') or (state == 'SP-'):
self.setStyleAttrib(colorDict, path, data['MI'])
return soup.prettify()
def writeFile(self, filename, data):
with open(filename, 'wb') as f:
f.write(data)
def readCSVtoDict(filename):
dataDict = {}
reader = csv.reader(open(filename))
for row in reader:
try:
dKey = row[0]
dVal = float(row[1].translate(None, ",$"))
dataDict[dKey] = dVal
except:
pass
return dataDict
iFile = os.path.dirname(__file__) + '\\data\\sales2013.csv'
stateSales = readCSVtoDict(iFile)
cDict = OrderedDict([('#DCFAE2', 0), ('#87EA9D', 10000), ('#00AD3B', 50000),
('#007829', 100000), ('#004216', 200000), ('#001708', 500000)])
NewMap = ColorStateMap(cDict, stateSales, 'coloredmap.svg')