def drawPlot(shapeFilename, zipBorough): # Read the ShapeFile dat = shapefile.Reader(shapeFilename) # Creates a dictionary for zip: {lat_list: [], lng_list: []}. zipCodes = [] polygons = {'lat_list': [], 'lng_list': []} record_index = 0 for r in dat.iterRecords(): currentZip = r[0] # Keeps only zip codes in NY area. if currentZip in zipBorough: zipCodes.append(currentZip) # Gets shape for this zip. shape = dat.shapeRecord(record_index).shape for part in range(len(shape.parts)): start = shape.parts[part] if part == len(shape.parts) - 1: end = len(shape.points) else: end = shape.parts[part + 1] points = shape.points[start : end] # Breaks into lists for lat/lng. lngs = [p[0] for p in points] lats = [p[1] for p in points] # Stores lat/lng for current zip shape. polygons['lng_list'].append(lngs) polygons['lat_list'].append(lats) record_index += 1 # Creates the Plot bk.output_file("zipCodes.html") bk.hold() TOOLS="pan,wheel_zoom,box_zoom,reset,previewsave" bk.figure(title="Zip codes in NY", \ tools=TOOLS, plot_width=1200, plot_height=800) # Creates the polygons. bk.patches(polygons['lng_list'], polygons['lat_list'], \ fill_color='#fee8c8', line_color="gray") bk.show()
def drawPlot(shapeFilename, zipBorough): # Read the ShapeFile dat = shapefile.Reader(shapeFilename) # Creates a dictionary for zip: {lat_list: [], lng_list: []}. zipCodes = [] polygons = {'lat_list': [], 'lng_list': []} record_index = 0 for r in dat.iterRecords(): currentZip = r[0] # Keeps only zip codes in NY area. if currentZip in zipBorough: zipCodes.append(currentZip) # Gets shape for this zip. shape = dat.shapeRecord(record_index).shape for part in range(len(shape.parts)): start = shape.parts[part] if part == len(shape.parts) - 1: end = len(shape.points) else: end = shape.parts[part + 1] points = shape.points[start:end] # Breaks into lists for lat/lng. lngs = [p[0] for p in points] lats = [p[1] for p in points] # Stores lat/lng for current zip shape. polygons['lng_list'].append(lngs) polygons['lat_list'].append(lats) record_index += 1 # Creates the Plot bk.output_file("zipCodes.html") bk.hold() TOOLS = "pan,wheel_zoom,box_zoom,reset,previewsave" bk.figure(title="Zip codes in NY", \ tools=TOOLS, plot_width=1200, plot_height=800) # Creates the polygons. bk.patches(polygons['lng_list'], polygons['lat_list'], \ fill_color='#fee8c8', line_color="gray") bk.show()
def getHTML(self, params): state = params['state'] if state == 'all': data = self.data else: data = self.data[self.data['state'] == state] TOOLS = "pan,wheel_zoom,box_zoom,reset,hover,previewsave" try: fig = plotting.patches(data['lons'], data['lats'], fill_color=data['color'], fill_alpha=0.7, tools=TOOLS, line_color="white", line_width=0.5, title=state.upper() + " Unemployment 2009") except Exception: fig = plotting.figure(title=state.upper() + " Unemployment 2009", tools=TOOLS) fig.patches(data['lons'], data['lats'], fill_color=data['color'], fill_alpha=0.7, line_color="white", line_width=0.5) hover = fig.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([("index", "$index")]) script, div = components(fig, CDN) html = "%s\n%s" % (script, div) return html
def getHTML(self, params): state = params['state'] if state == 'all': data = self.data else: data = self.data[self.data['state'] == state] TOOLS = "pan,wheel_zoom,box_zoom,reset,hover,previewsave" try: fig = plotting.patches( data['lons'], data['lats'], fill_color=data['color'], fill_alpha=0.7, tools=TOOLS, line_color="white", line_width=0.5, title=state.upper() + " Unemployment 2009" ) except Exception: fig = plotting.figure(title=state.upper() + " Unemployment 2009", tools=TOOLS) fig.patches( data['lons'], data['lats'], fill_color=data['color'], fill_alpha=0.7, line_color="white", line_width=0.5 ) hover = fig.select(dict(type=HoverTool)) hover.tooltips = OrderedDict([ ("index", "$index") ]) script, div = components(fig, CDN) html = "%s\n%s" % (script, div) return html
def generate_webpage(): # Read the ShapeFile dat = shapefile.Reader("./shapefile/USCounties.shp") d = anova.average_user_scores() d2 = anova.county_results(d) average_scores = county_means(d2) a2 = dict() for key in average_scores.keys(): new_key = key[0].strip('City').strip('County').strip(' ') a2[(new_key, key[1])] = average_scores[key] min_score = min(a2.values()) palette = ["#FFF7EC", "#FEE8C8", "#FDD49E", "#FDBB84", "#FC8D59", "#EF6548", "#D7301F", "#B30000", "#7F0000"] colors = dict() for county in a2: colors[county] = get_color(a2[county], min_score, palette) # Create a list of county tuples of (County, State) counties = [(i[0], i[1]) for i in dat.iterRecords()] # Create the Plot bp.output_file("us_counties.html") TOOLS="pan,wheel_zoom,box_zoom,reset,previewsave" bp.figure(title="Average county-level sentiment, 2009", tools=TOOLS, plot_width=900, plot_height=800) bp.hold() count = 0 for county in counties: data = getDict(county, dat) if county in colors: fill = colors[county] else: fill = "#20B2AA" bp.patches(data[(county[0], county[1])]['lat_list'], data[(county[0], county[1])]['lng_list'], \ fill_color = fill, line_color = "black") bp.show()
def drawPlot(shapeFilename, zipBorough, zipMaxAgency): # Read the ShapeFile dat = shapefile.Reader(shapeFilename) # Creates a dictionary for zip: {lat_list: [], lng_list: []}. zipCodes = [] hoverZip = [] hoverAgency = [] hoverComplaints = [] polygons = {'lat_list': [], 'lng_list': [], 'centerLat_list': [], 'centerLon_list': []} record_index = 0 for r in dat.iterRecords(): currentZip = r[0] # Keeps only zip codes in NY area. if currentZip in zipMaxAgency: # was in zipBorough: # zipCodes.append(currentZip) # moving this line into the parts loop # Gets shape for this zip. shape = dat.shapeRecord(record_index).shape for part in range(len(shape.parts)): zipCodes.append(currentZip) hoverZip.append(currentZip) hoverAgency.append(zipMaxAgency[currentZip][0]) hoverComplaints.append(zipMaxAgency[currentZip][1]) start = shape.parts[part] if part == len(shape.parts) - 1: end = len(shape.points) else: end = shape.parts[part + 1] points = shape.points[start : end] # Breaks into lists for lat/lng. lngs = [p[0] for p in points] lats = [p[1] for p in points] # Calculate centers center_lngs = min(lngs) + (max(lngs) - min(lngs))/2 center_lats = min(lats) + (max(lats) - min(lats))/2 # Store centroids for current part shape polygons['centerLat_list'].append(center_lats) polygons['centerLon_list'].append(center_lngs) # Stores lat/lng for current zip shape. polygons['lng_list'].append(lngs) polygons['lat_list'].append(lats) record_index += 1 # Palette ##d9d9d9 brewer11 = ['#8dd3c7', '#ffffb3', '#bebada','#fb8072','#80b1d3','#fdb462','#b3de69','#fccde5','#d9d9d9','#bc80bd','#ccebc5'] #brewer11 = ['#a6cee3', '#1f78b4','#b2df8a','#33a02c','#fb9a99','#e31a1c','#fdbf6f','#ff7f00','#cab2d6','#6a3d9a','#ffff99'] #agencies = sorted(list({zipMaxAgency[zipCode] for zipCode in zipMaxAgency})) biggestComplaints = {} for zz, aa in zipMaxAgency.iteritems(): if aa[0] in biggestComplaints: biggestComplaints[aa[0]] += 1 else: biggestComplaints[aa[0]] = 1 # sorting agencies by number of zip codes (to try to get better colors) agencies = list(biggestComplaints.iteritems()) agencies = sorted(agencies, key = lambda x: x[1], reverse = True) agencies = [agency[0] for agency in agencies] # Assign colors to agencies agencyColor = {agencies[i] : brewer11[i] for i in range(len(brewer11))} polygons['colors'] = [agencyColor[zipMaxAgency[zipCode][0]] for zipCode in zipCodes] # Prepare hover #source = bk.ColumnDataSource(data=dict(hoverAgency=hoverAgency, hoverZip=hoverZip, hoverComplaintCount=hoverComplaintCount,)) source = bk.ColumnDataSource(data=dict(hoverZip = hoverZip, hoverAgency = hoverAgency, hoverComplaints = hoverComplaints),) # Creates the Plot bk.output_file("problem1.html") bk.hold() TOOLS="pan,wheel_zoom,box_zoom,reset,previewsave,hover" fig = bk.figure(title="311 Complaints by Zip Code", \ tools=TOOLS, plot_width=800, plot_height=650) # Creates the polygons. bk.patches(polygons['lng_list'], polygons['lat_list'], fill_color=polygons['colors'], line_color="gray", source = source) # RP: add hover hover = bk.curplot().select(dict(type=HoverTool)) hover.tooltips = OrderedDict([ ("Zip", "@hoverZip"), ("Agency", "@hoverAgency"), ("Number of complaints", "@hoverComplaints"), ]) ### Zip codes as text on polygons #for i in range(len(polygons['centerLat_list'])): # y = polygons['centerLat_list'][i] # x = polygons['centerLon_list'][i] # zipCode = zipCodes[i] # bk.text([x], [y], text=zipCode, angle=0, text_font_size="8pt", text_align="center", text_baseline="middle") fonts = ["Comic sans MS", "Papyrus", "Curlz", "Impact", "Zapf dingbats", "Comic sans MS", "Papyrus", "Curlz", "Impact", "Zapf Dingbats", "Comic sans MS"] ### Legend x = -73.66 y = 40.50 #x = -74.25 #y = 40.9 for agency, color in agencyColor.iteritems(): #print "Color: ", a #print "x:", x #print "y:", y bk.rect([x], [y], color = color, width=0.03, height=0.015) bk.text([x], [y], text = agency, angle=0, text_font_size="7pt", text_align="center", text_baseline="middle") y = y + 0.015 #bokeh.embed.components(fig, bokeh.resources.CDN) bk.show()
def drawPlot(shapeFilename, zipBorough, grids, centers, gridLines): # Read the ShapeFile dat = shapefile.Reader(shapeFilename) # Creates a dictionary for zip: {lat_list: [], lng_list: []}. zipCodes = [] polygons = {'lat_list': [], 'lng_list': [], 'centerLat_list': [], 'centerLon_list': []} record_index = 0 for r in dat.iterRecords(): currentZip = r[0] # Keeps only zip codes in NY area. if currentZip in zipBorough: # was in zipBorough: # Gets shape for this zip. shape = dat.shapeRecord(record_index).shape for part in range(len(shape.parts)): zipCodes.append(currentZip) start = shape.parts[part] if part == len(shape.parts) - 1: end = len(shape.points) else: end = shape.parts[part + 1] points = shape.points[start : end] # Breaks into lists for lat/lng. lngs = [p[0] for p in points] lats = [p[1] for p in points] # Calculate centers center_lngs = min(lngs) + (max(lngs) - min(lngs))/2 center_lats = min(lats) + (max(lats) - min(lats))/2 # Store centroids for current part shape polygons['centerLat_list'].append(center_lats) polygons['centerLon_list'].append(center_lngs) # Stores lat/lng for current zip shape. polygons['lng_list'].append(lngs) polygons['lat_list'].append(lats) record_index += 1 # Creates the Plot bk.output_file("problem3.html") bk.hold() north = 40.915 east = -73.651 south = 40.496 west = -74.256 width = east - west height = north - south x_range = [west - 0.05 * width, east + 0.05 * width] y_range = [south - 0.05 * height, north + 0.05 * height] TOOLS="pan,wheel_zoom,box_zoom,reset,previewsave" fig = bk.figure(title="311 Complaints by Zip Code", \ tools=TOOLS, background_fill = "#f8f8f8", x_range = x_range, y_range = y_range) circleSizes = [item for sublist in grids['log_counts'] for item in sublist] # Creates the polygons cellWidth = gridLines['vLines'][1]-gridLines['vLines'][0] cellHeight = gridLines['hLines'][1] - gridLines['hLines'][0] bk.patches(polygons['lng_list'], polygons['lat_list'], fill_color="#fee8c8", line_color="gray") circleSizes = [0.009 * (size ** 3.7) for size in circleSizes] bk.scatter(centers['lon'], centers['lat'], size = circleSizes, alpha = 0.4, line_color = None, fill_color = 'red') bk.hold() #print type(centers['lon']) circleSizeArr = np.array(circleSizes) maxSize = np.max(circleSizeArr) circleSizeArr[circleSizeArr == 0] = 100 minSize = np.min(circleSizeArr) #print minSize, maxSize legendN = 5 legendCircles = list(np.linspace(minSize, maxSize, legendN)) legendCounts = [str(int(math.exp(((size/0.009) ** (1.0/3.7))))) + " complaints" for size in legendCircles] #print legendCircles fakeScatter = [0 for x in range(legendN)] fakeScatterX = [-74.23 for x in range(legendN)] fakeScatterXtext = [-74.23 + 0.05 for x in range(legendN)] #fakeScatterY = [40.8 + 0.028*y for y in range(legendN)] fakeScatterY = [40.8, 40.8 + 0.02, 40.8 + 0.036, 40.8 + 0.056,40.8 + 0.083] #print fakeScatterX, type(fakeScatterX) #print fakeScatterY, type(fakeScatterY) bk.scatter(fakeScatterX, fakeScatterY, size = legendCircles, fill_color = 'red', line_color = None, alpha = 0.4) bk.text(fakeScatterXtext[1:], fakeScatterY[1:], text = legendCounts[1:], angle = 0, text_align = "left", text_font_size = "7pt", text_baseline = 'middle') #for i in range(len(fakeScatter)): # bk.scatter([fakeScatter[i]], [fakeScatter[i]], size = [legendCircles[i]], legend = int(legendCircles[i]), color = 'red', fill_line = None, alpha = 0.4) # Disable background grid bk.grid().grid_line_color = None #print centers ### Legend #x = -74.25 #y = 40.8 #height = 0.003 #legend_box_y = y + 0.5 * height * len(legendColors) #bk.rect([x+0.032], [legend_box_y], width = 0.12, height = height*len(legendColors)*1.15, color = "#ffffff", line_color = "gray") ##x = -74.25 ##y = 40.9 #for color in legendColors: ## #print "Color: ", a ## #print "x:", x ## #print "y:", y ## # bk.rect([x], [y], color = color, width=0.03, height=height) # #bk.text([x], [y], text = agency, angle=0, text_font_size="7pt", text_align="center", text_baseline="middle") # y = y + height #legend_bottom_y = 40.797 #legend_top_y = legend_bottom_y + 0.92 * height * len(legendColors) #bk.text([-74.225], [legend_bottom_y], text = agency2, angle = 0, text_font_size = "7pt", text_align = "left") #bk.text([-74.225], [legend_top_y], text = agency1, angle = 0, text_font_size = "7pt", text_align = "left") #bokeh.embed.components(fig, bokeh.resources.CDN) bk.show()
def drawPlot(shapeFilename, zipBorough, zipMaxAgency): # Read the ShapeFile dat = shapefile.Reader(shapeFilename) # Creates a dictionary for zip: {lat_list: [], lng_list: []}. zipCodes = [] hoverZip = [] hoverAgency = [] hoverComplaints = [] polygons = { 'lat_list': [], 'lng_list': [], 'centerLat_list': [], 'centerLon_list': [] } record_index = 0 for r in dat.iterRecords(): currentZip = r[0] # Keeps only zip codes in NY area. if currentZip in zipMaxAgency: # was in zipBorough: # zipCodes.append(currentZip) # moving this line into the parts loop # Gets shape for this zip. shape = dat.shapeRecord(record_index).shape for part in range(len(shape.parts)): zipCodes.append(currentZip) hoverZip.append(currentZip) hoverAgency.append(zipMaxAgency[currentZip][0]) hoverComplaints.append(zipMaxAgency[currentZip][1]) start = shape.parts[part] if part == len(shape.parts) - 1: end = len(shape.points) else: end = shape.parts[part + 1] points = shape.points[start:end] # Breaks into lists for lat/lng. lngs = [p[0] for p in points] lats = [p[1] for p in points] # Calculate centers center_lngs = min(lngs) + (max(lngs) - min(lngs)) / 2 center_lats = min(lats) + (max(lats) - min(lats)) / 2 # Store centroids for current part shape polygons['centerLat_list'].append(center_lats) polygons['centerLon_list'].append(center_lngs) # Stores lat/lng for current zip shape. polygons['lng_list'].append(lngs) polygons['lat_list'].append(lats) record_index += 1 # Palette ##d9d9d9 brewer11 = [ '#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3', '#fdb462', '#b3de69', '#fccde5', '#d9d9d9', '#bc80bd', '#ccebc5' ] #brewer11 = ['#a6cee3', '#1f78b4','#b2df8a','#33a02c','#fb9a99','#e31a1c','#fdbf6f','#ff7f00','#cab2d6','#6a3d9a','#ffff99'] #agencies = sorted(list({zipMaxAgency[zipCode] for zipCode in zipMaxAgency})) biggestComplaints = {} for zz, aa in zipMaxAgency.iteritems(): if aa[0] in biggestComplaints: biggestComplaints[aa[0]] += 1 else: biggestComplaints[aa[0]] = 1 # sorting agencies by number of zip codes (to try to get better colors) agencies = list(biggestComplaints.iteritems()) agencies = sorted(agencies, key=lambda x: x[1], reverse=True) agencies = [agency[0] for agency in agencies] # Assign colors to agencies agencyColor = {agencies[i]: brewer11[i] for i in range(len(brewer11))} polygons['colors'] = [ agencyColor[zipMaxAgency[zipCode][0]] for zipCode in zipCodes ] # Prepare hover #source = bk.ColumnDataSource(data=dict(hoverAgency=hoverAgency, hoverZip=hoverZip, hoverComplaintCount=hoverComplaintCount,)) source = bk.ColumnDataSource(data=dict(hoverZip=hoverZip, hoverAgency=hoverAgency, hoverComplaints=hoverComplaints), ) # Creates the Plot bk.output_file("problem1.html") bk.hold() TOOLS = "pan,wheel_zoom,box_zoom,reset,previewsave,hover" fig = bk.figure(title="311 Complaints by Zip Code", \ tools=TOOLS, plot_width=800, plot_height=650) # Creates the polygons. bk.patches(polygons['lng_list'], polygons['lat_list'], fill_color=polygons['colors'], line_color="gray", source=source) # RP: add hover hover = bk.curplot().select(dict(type=HoverTool)) hover.tooltips = OrderedDict([ ("Zip", "@hoverZip"), ("Agency", "@hoverAgency"), ("Number of complaints", "@hoverComplaints"), ]) ### Zip codes as text on polygons #for i in range(len(polygons['centerLat_list'])): # y = polygons['centerLat_list'][i] # x = polygons['centerLon_list'][i] # zipCode = zipCodes[i] # bk.text([x], [y], text=zipCode, angle=0, text_font_size="8pt", text_align="center", text_baseline="middle") fonts = [ "Comic sans MS", "Papyrus", "Curlz", "Impact", "Zapf dingbats", "Comic sans MS", "Papyrus", "Curlz", "Impact", "Zapf Dingbats", "Comic sans MS" ] ### Legend x = -73.66 y = 40.50 #x = -74.25 #y = 40.9 for agency, color in agencyColor.iteritems(): #print "Color: ", a #print "x:", x #print "y:", y bk.rect([x], [y], color=color, width=0.03, height=0.015) bk.text([x], [y], text=agency, angle=0, text_font_size="7pt", text_align="center", text_baseline="middle") y = y + 0.015 #bokeh.embed.components(fig, bokeh.resources.CDN) bk.show()
def drawPlot(shapeFilename, zipBorough, grids, centers, gridLines): # Read the ShapeFile dat = shapefile.Reader(shapeFilename) # Creates a dictionary for zip: {lat_list: [], lng_list: []}. zipCodes = [] polygons = { 'lat_list': [], 'lng_list': [], 'centerLat_list': [], 'centerLon_list': [] } record_index = 0 for r in dat.iterRecords(): currentZip = r[0] # Keeps only zip codes in NY area. if currentZip in zipBorough: # was in zipBorough: # Gets shape for this zip. shape = dat.shapeRecord(record_index).shape for part in range(len(shape.parts)): zipCodes.append(currentZip) start = shape.parts[part] if part == len(shape.parts) - 1: end = len(shape.points) else: end = shape.parts[part + 1] points = shape.points[start:end] # Breaks into lists for lat/lng. lngs = [p[0] for p in points] lats = [p[1] for p in points] # Calculate centers center_lngs = min(lngs) + (max(lngs) - min(lngs)) / 2 center_lats = min(lats) + (max(lats) - min(lats)) / 2 # Store centroids for current part shape polygons['centerLat_list'].append(center_lats) polygons['centerLon_list'].append(center_lngs) # Stores lat/lng for current zip shape. polygons['lng_list'].append(lngs) polygons['lat_list'].append(lats) record_index += 1 # Creates the Plot bk.output_file("problem3.html") bk.hold() north = 40.915 east = -73.651 south = 40.496 west = -74.256 width = east - west height = north - south x_range = [west - 0.05 * width, east + 0.05 * width] y_range = [south - 0.05 * height, north + 0.05 * height] TOOLS = "pan,wheel_zoom,box_zoom,reset,previewsave" fig = bk.figure(title="311 Complaints by Zip Code", \ tools=TOOLS, background_fill = "#f8f8f8", x_range = x_range, y_range = y_range) circleSizes = [item for sublist in grids['log_counts'] for item in sublist] # Creates the polygons cellWidth = gridLines['vLines'][1] - gridLines['vLines'][0] cellHeight = gridLines['hLines'][1] - gridLines['hLines'][0] bk.patches(polygons['lng_list'], polygons['lat_list'], fill_color="#fee8c8", line_color="gray") circleSizes = [0.009 * (size**3.7) for size in circleSizes] bk.scatter(centers['lon'], centers['lat'], size=circleSizes, alpha=0.4, line_color=None, fill_color='red') bk.hold() #print type(centers['lon']) circleSizeArr = np.array(circleSizes) maxSize = np.max(circleSizeArr) circleSizeArr[circleSizeArr == 0] = 100 minSize = np.min(circleSizeArr) #print minSize, maxSize legendN = 5 legendCircles = list(np.linspace(minSize, maxSize, legendN)) legendCounts = [ str(int(math.exp(((size / 0.009)**(1.0 / 3.7))))) + " complaints" for size in legendCircles ] #print legendCircles fakeScatter = [0 for x in range(legendN)] fakeScatterX = [-74.23 for x in range(legendN)] fakeScatterXtext = [-74.23 + 0.05 for x in range(legendN)] #fakeScatterY = [40.8 + 0.028*y for y in range(legendN)] fakeScatterY = [ 40.8, 40.8 + 0.02, 40.8 + 0.036, 40.8 + 0.056, 40.8 + 0.083 ] #print fakeScatterX, type(fakeScatterX) #print fakeScatterY, type(fakeScatterY) bk.scatter(fakeScatterX, fakeScatterY, size=legendCircles, fill_color='red', line_color=None, alpha=0.4) bk.text(fakeScatterXtext[1:], fakeScatterY[1:], text=legendCounts[1:], angle=0, text_align="left", text_font_size="7pt", text_baseline='middle') #for i in range(len(fakeScatter)): # bk.scatter([fakeScatter[i]], [fakeScatter[i]], size = [legendCircles[i]], legend = int(legendCircles[i]), color = 'red', fill_line = None, alpha = 0.4) # Disable background grid bk.grid().grid_line_color = None #print centers ### Legend #x = -74.25 #y = 40.8 #height = 0.003 #legend_box_y = y + 0.5 * height * len(legendColors) #bk.rect([x+0.032], [legend_box_y], width = 0.12, height = height*len(legendColors)*1.15, color = "#ffffff", line_color = "gray") ##x = -74.25 ##y = 40.9 #for color in legendColors: ## #print "Color: ", a ## #print "x:", x ## #print "y:", y ## # bk.rect([x], [y], color = color, width=0.03, height=height) # #bk.text([x], [y], text = agency, angle=0, text_font_size="7pt", text_align="center", text_baseline="middle") # y = y + height #legend_bottom_y = 40.797 #legend_top_y = legend_bottom_y + 0.92 * height * len(legendColors) #bk.text([-74.225], [legend_bottom_y], text = agency2, angle = 0, text_font_size = "7pt", text_align = "left") #bk.text([-74.225], [legend_top_y], text = agency1, angle = 0, text_font_size = "7pt", text_align = "left") #bokeh.embed.components(fig, bokeh.resources.CDN) bk.show()
def drawPlot(shapeFilename, zipBorough, zipCount): # Read the ShapeFile dat = shapefile.Reader(shapeFilename) # Creates a dictionary for zip: {lat_list: [], lng_list: []}. zipCodes = [] polygons = {'lat_list': [], 'lng_list': [], 'centerLat_list': [], 'centerLon_list': []} record_index = 0 for r in dat.iterRecords(): currentZip = r[0] # Keeps only zip codes in NY area. if currentZip in zipBorough: # was in zipBorough: # Gets shape for this zip. shape = dat.shapeRecord(record_index).shape ### Only first polygon if non-contiguous zip codes #firstPoint = shape.parts[0] #if len(shape.parts) > 1: # lastPoint = shape.parts[1] #else: # lastPoint = len(shape.points) #zipCodes.append(currentZip) #points = shape.points[firstPoint : lastPoint] # ## Breaks into lists for lat/lng. #lngs = [p[0] for p in points] #lats = [p[1] for p in points] ## Calculate centers #center_lngs = min(lngs) + (max(lngs) - min(lngs))/2 #center_lats = min(lats) + (max(lats) - min(lats))/2 ## Store centroids for current part shape #polygons['centerLat_list'].append(center_lats) #polygons['centerLon_list'].append(center_lngs) ## Stores lat/lng for current zip shape. #polygons['lng_list'].append(lngs) #polygons['lat_list'].append(lats) ### All shapes for each zip code for part in range(len(shape.parts)): zipCodes.append(currentZip) start = shape.parts[part] if part == len(shape.parts) - 1: end = len(shape.points) else: end = shape.parts[part + 1] points = shape.points[start : end] # Breaks into lists for lat/lng. lngs = [p[0] for p in points] lats = [p[1] for p in points] # Calculate centers center_lngs = min(lngs) + (max(lngs) - min(lngs))/2 center_lats = min(lats) + (max(lats) - min(lats))/2 # Store centroids for current part shape polygons['centerLat_list'].append(center_lats) polygons['centerLon_list'].append(center_lngs) # Stores lat/lng for current zip shape. polygons['lng_list'].append(lngs) polygons['lat_list'].append(lats) record_index += 1 # Creates the Plot bk.output_file("problem4.html") bk.hold() north = 40.915 east = -73.651 south = 40.496 west = -74.256 width = east - west height = north - south x_range = [west - 0.05 * width, east + 0.05 * width] y_range = [south - 0.05 * height, north + 0.05 * height] TOOLS="pan,wheel_zoom,box_zoom,reset,previewsave" fig = bk.figure(title="311 Complaints by Zip Code", \ tools=TOOLS, background_fill = "#f8f8f8", x_range = x_range, y_range = y_range, plot_height=800, plot_width = 1200) #circleSizes = [zipCount[zipCode] for zipCode in zipCodes] circleSizes = [] for zipCode in zipCodes: if zipCode in zipCount: circleSizes.append(zipCount[zipCode]) else: circleSizes.append(1) # for taking logs #print circleSizes #print "aaaaaaaaaaaaaaaaaaaaa: ", len(polygons['lng_list']), len(circleSizes) logCircleSizes = ((np.log(np.array(circleSizes)))**3.7) * 0.009 #print logCircleSizes logCircleSizes = list(logCircleSizes) #circleSizes = [x for x in range(len(zipCodes))] # Creates the polygons bk.patches(polygons['lng_list'], polygons['lat_list'], fill_color="#fee8c8", line_color="gray") bk.scatter(polygons['centerLon_list'], polygons['centerLat_list'], size = logCircleSizes, alpha = 0.4, line_color = None, fill_color = 'red') #circleSizes = [0.009 * (size ** 3.7) for size in circleSizes] #bk.scatter(centers['lon'], centers['lat'], size = circleSizes, alpha = 0.4, line_color = None, fill_color = 'red') #circleSizeArr = np.array(circleSizes) #maxSize = np.max(circleSizeArr) #circleSizeArr[circleSizeArr == 0] = 100 #minSize = np.min(circleSizeArr) #legendN = 5 #legendCircles = list(np.linspace(minSize, maxSize, legendN)) #legendCounts = [str(int((size ** (1.0/3.7))/0.009)) + " complaints" for size in legendCircles] #fakeScatter = [0 for x in range(legendN)] #fakeScatterX = [-74.23 for x in range(legendN)] #fakeScatterXtext = [-74.23 + 0.05 for x in range(legendN)] #fakeScatterY = [40.8, 40.8 + 0.02, 40.8 + 0.036, 40.8 + 0.056,40.8 + 0.083] #bk.scatter(fakeScatterX, fakeScatterY, size = legendCircles, fill_color = 'red', line_color = None, alpha = 0.4) #bk.text(fakeScatterXtext[1:], fakeScatterY[1:], text = legendCounts[1:], angle = 0, text_align = "left", text_font_size = "7pt", text_baseline = 'middle') # Disable background grid bk.grid().grid_line_color = None bk.show()
def drawPlot(shapeFilename, zipBorough, zipCount): # Read the ShapeFile dat = shapefile.Reader(shapeFilename) # Creates a dictionary for zip: {lat_list: [], lng_list: []}. zipCodes = [] polygons = { 'lat_list': [], 'lng_list': [], 'centerLat_list': [], 'centerLon_list': [] } record_index = 0 for r in dat.iterRecords(): currentZip = r[0] # Keeps only zip codes in NY area. if currentZip in zipBorough: # was in zipBorough: # Gets shape for this zip. shape = dat.shapeRecord(record_index).shape ### Only first polygon if non-contiguous zip codes #firstPoint = shape.parts[0] #if len(shape.parts) > 1: # lastPoint = shape.parts[1] #else: # lastPoint = len(shape.points) #zipCodes.append(currentZip) #points = shape.points[firstPoint : lastPoint] # ## Breaks into lists for lat/lng. #lngs = [p[0] for p in points] #lats = [p[1] for p in points] ## Calculate centers #center_lngs = min(lngs) + (max(lngs) - min(lngs))/2 #center_lats = min(lats) + (max(lats) - min(lats))/2 ## Store centroids for current part shape #polygons['centerLat_list'].append(center_lats) #polygons['centerLon_list'].append(center_lngs) ## Stores lat/lng for current zip shape. #polygons['lng_list'].append(lngs) #polygons['lat_list'].append(lats) ### All shapes for each zip code for part in range(len(shape.parts)): zipCodes.append(currentZip) start = shape.parts[part] if part == len(shape.parts) - 1: end = len(shape.points) else: end = shape.parts[part + 1] points = shape.points[start:end] # Breaks into lists for lat/lng. lngs = [p[0] for p in points] lats = [p[1] for p in points] # Calculate centers center_lngs = min(lngs) + (max(lngs) - min(lngs)) / 2 center_lats = min(lats) + (max(lats) - min(lats)) / 2 # Store centroids for current part shape polygons['centerLat_list'].append(center_lats) polygons['centerLon_list'].append(center_lngs) # Stores lat/lng for current zip shape. polygons['lng_list'].append(lngs) polygons['lat_list'].append(lats) record_index += 1 # Creates the Plot bk.output_file("problem4.html") bk.hold() north = 40.915 east = -73.651 south = 40.496 west = -74.256 width = east - west height = north - south x_range = [west - 0.05 * width, east + 0.05 * width] y_range = [south - 0.05 * height, north + 0.05 * height] TOOLS = "pan,wheel_zoom,box_zoom,reset,previewsave" fig = bk.figure(title="311 Complaints by Zip Code", \ tools=TOOLS, background_fill = "#f8f8f8", x_range = x_range, y_range = y_range, plot_height=800, plot_width = 1200) #circleSizes = [zipCount[zipCode] for zipCode in zipCodes] circleSizes = [] for zipCode in zipCodes: if zipCode in zipCount: circleSizes.append(zipCount[zipCode]) else: circleSizes.append(1) # for taking logs #print circleSizes #print "aaaaaaaaaaaaaaaaaaaaa: ", len(polygons['lng_list']), len(circleSizes) logCircleSizes = ((np.log(np.array(circleSizes)))**3.7) * 0.009 #print logCircleSizes logCircleSizes = list(logCircleSizes) #circleSizes = [x for x in range(len(zipCodes))] # Creates the polygons bk.patches(polygons['lng_list'], polygons['lat_list'], fill_color="#fee8c8", line_color="gray") bk.scatter(polygons['centerLon_list'], polygons['centerLat_list'], size=logCircleSizes, alpha=0.4, line_color=None, fill_color='red') #circleSizes = [0.009 * (size ** 3.7) for size in circleSizes] #bk.scatter(centers['lon'], centers['lat'], size = circleSizes, alpha = 0.4, line_color = None, fill_color = 'red') #circleSizeArr = np.array(circleSizes) #maxSize = np.max(circleSizeArr) #circleSizeArr[circleSizeArr == 0] = 100 #minSize = np.min(circleSizeArr) #legendN = 5 #legendCircles = list(np.linspace(minSize, maxSize, legendN)) #legendCounts = [str(int((size ** (1.0/3.7))/0.009)) + " complaints" for size in legendCircles] #fakeScatter = [0 for x in range(legendN)] #fakeScatterX = [-74.23 for x in range(legendN)] #fakeScatterXtext = [-74.23 + 0.05 for x in range(legendN)] #fakeScatterY = [40.8, 40.8 + 0.02, 40.8 + 0.036, 40.8 + 0.056,40.8 + 0.083] #bk.scatter(fakeScatterX, fakeScatterY, size = legendCircles, fill_color = 'red', line_color = None, alpha = 0.4) #bk.text(fakeScatterXtext[1:], fakeScatterY[1:], text = legendCounts[1:], angle = 0, text_align = "left", text_font_size = "7pt", text_baseline = 'middle') # Disable background grid bk.grid().grid_line_color = None bk.show()