# Population Map Generator # Created by Jason Godwin (21 February 2012) # Acknowledgements: # # Code derived from Nathan Yau's unemployment map # County map SVG from Wikimedia Commons # Population data from the United States Census Bureau # # Links: # # Unemployment map: http://flowingdata.com/2009/11/12/how-to-make-a-us-county-thematic-map-using-free-tools/ # SVG Map: http://commons.wikimedia.org/wiki/File:USA_Counties_with_FIPS_and_names.svg # US Census Bureau: http://www.census.gov # # Contact information: # # Email: jwgodwin@ou.edu # Website: http://www.jasonsweathercenter.com # # Updates # Version 1.1 (2/22/12): Added capabilities for plotting land area and # population density. # Import libraries import csv import sys from BeautifulSoup import BeautifulSoup # Ask user what to plot #print "1 - Population" #print "2 - Land area" #print "3 - Population Density" selector = input() if selector == 1: data_type = 1 elif selector == 2: data_type = 2 elif selector == 3: data_type = 3 else: exit() # Read in populations population = {} min_value = 0; max_value = 10000000; reader = csv.reader(open('Population2010.csv'), delimiter=",") for row in reader: try: full_fips = row[0] pop = float( row[data_type].strip() ) population[full_fips] = pop except: pass # Load the SVG Map svg = open('counties.svg', 'r').read() # Load into Beautiful Soup soup = BeautifulSoup(svg, selfClosingTags=['defs','sodipodi:namedview']) # Find counties paths = soup.findAll('path') # Map colors colors = ["#FFFFCC", "#FFEDA0", "#FED976", "#FEB24C", "#FD8D3C", "#FC4E2A", "#E31A1C", "#BD0026", "#800026"] # County style path_style = 'font-size:12px;fill-rule:nonzero;stroke:#FFFFFF;stroke-opacity:1;stroke-width:0.1;stroke-miterlimit:4;stroke-dasharray:none;stroke-linecap:butt;marker-start:none;stroke-linejoin:bevel;fill:' # Specify color levels based on data type if data_type == 1: # set the population limits classA = 1000000 classB = 750000 classC = 500000 classD = 250000 classE = 100000 classF = 50000 classG = 25000 classH = 10000 elif data_type == 2: # set the area limits (units of sq. miles) classA = 10000 classB = 7500 classC = 5000 classD = 2500 classE = 1000 classF = 500 classG = 250 classH = 100 elif data_type == 3: # set the pop. density limits (people/sq mi) classA = 1000 classB = 750 classC = 500 classD = 250 classE = 100 classF = 50 classG = 25 classH = 10 else: print('Program error!') exit() # Color counties based on unemployment rate for p in paths: if p['id'] not in ["State_Lines", "separator"]: # pass try: pop = population[p['id']] except: continue if pop > classA: color_class = 8 elif pop > classB: color_class = 7 elif pop > classC: color_class = 6 elif pop > classD: color_class = 5 elif pop > classE: color_class = 4 elif pop > classF: color_class = 3 elif pop > classG: color_class = 2 elif pop > classH: color_class = 1 else: color_class = 0 color = colors[color_class] p['style'] = path_style + color # Output map print soup.prettify()