def plot(location, predictions,state_name): from bokeh.sampledata.us_counties import data as counties palette.reverse() counties = {code: county for code, county in counties.items() if county["state"] in [state_name]} county_xs = [county["lons"] for county in counties.values()] county_ys = [county["lats"] for county in counties.values()] county_names = [county['name'] for county in counties.values()]#Make sure names match with data county_rates = [unemployment[county_id] for county_id in counties]#These would be the predictions #color_mapper = LogColorMapper(palette=palette) color_mapper = LinearColorMapper(palette=palette,low=25, high=75) data=dict(x=county_xs,y=county_ys,name=county_names,rate=predictions,) TOOLS = "pan,wheel_zoom,reset,hover,save" p = figure(title="Vote Preference Predictions", tools=TOOLS, plot_width=900, #x_axis_location=None, y_axis_location=None,tooltips=[("Name", "@name"), ("Unemployment rate)", "@rate%"), ("(Long, Lat)", "($x, $y)")]) x_axis_location=None, y_axis_location=None,tooltips=[("Name", "@name"), ("Yes vote (percent)", "@rate%")]) p.grid.grid_line_color = None p.hover.point_policy = "follow_mouse" p.patches('x', 'y', source=data,fill_color={'field': 'rate', 'transform': color_mapper},fill_alpha=1.0, line_color="white", line_width=0.5) script, div = components(p) return script, div
def bokeh_chloropleth(state, values): """Creates a Bokeh chloropleth for a given state's counties given values. Args: state (str): The state to analyze. values (list): A list of county values. """ # Define county shapes. counties = { code: county for code, county in counties.items() if county["state"] == state } county_xs = [county["lons"] for county in counties.values()] county_ys = [county["lats"] for county in counties.values()] county_names = [county['name'] for county in counties.values()] # Define county values # county_rates = [unemployment[county_id] for county_id in counties] color_mapper = LogColorMapper(palette=palette) data = dict( x=county_xs, y=county_ys, name=county_names, value=values, ) TOOLS = "pan,wheel_zoom,reset,hover,save" p = figure(title="Washington State Cannabis Cultivators", tools=TOOLS, x_axis_location=None, y_axis_location=None, tooltips=[("Name", "@name"), ("Number", "@value%"), ("(Long, Lat)", "($x, $y)")]) p.grid.grid_line_color = None p.hover.point_policy = "follow_mouse" p.patches('x', 'y', source=data, fill_color={ 'field': 'value', 'transform': color_mapper }, fill_alpha=0.7, line_color="white", line_width=0.5, plot_width=800, plot_height=500) show(p) return p
def plot(location, predictions, state_name): from bokeh.sampledata.us_counties import data as counties #print(counties.keys()) counties = { code: county for code, county in counties.items() if county["state"] in [state_name] } print(len(counties)) #print(type(counties)) county_xs = [county["lons"] for county in counties.values()] county_ys = [county["lats"] for county in counties.values()] county_names = [county['name'] for county in counties.values() ] #Make sure names match with data print(county_names) color_mapper = LinearColorMapper(palette=palette, low=25, high=75) data = dict( x=county_xs, y=county_ys, name=county_names, rate=predictions, ) TOOLS = "pan,wheel_zoom,reset,hover,save" p = figure(title="Vote Preference Predictions", tools=TOOLS, plot_width=900, x_axis_location=None, y_axis_location=None, tooltips=[("Name", "@name"), ("Yes vote (percent)", "@rate%")]) color_bar = ColorBar(color_mapper=color_mapper, ticker=LogTicker(), label_standoff=12, border_line_color=None, location=(0, 0)) p.add_layout(color_bar, 'right') p.grid.grid_line_color = None p.hover.point_policy = "follow_mouse" p.patches('x', 'y', source=data, fill_color={ 'field': 'rate', 'transform': color_mapper }, fill_alpha=1.0, line_color="white", line_width=0.5) script, div = components(p) return script, div
def bokehPlot(p): from bokeh.io import show from bokeh.models import LogColorMapper from bokeh.palettes import Viridis6 as palette try: from bokeh.sampledata.unemployment import data as unemployment from bokeh.sampledata.us_counties import data as counties except: import bokeh bokeh.sampledata.download() from bokeh.sampledata.unemployment import data as unemployment from bokeh.sampledata.us_counties import data as counties palette = tuple(reversed(palette)) counties = { code: county for code, county in counties.items() if county["state"] == "tx" } county_xs = [county["lons"] for county in counties.values()] county_ys = [county["lats"] for county in counties.values()] county_names = [county['name'] for county in counties.values()] county_rates = [unemployment[county_id] for county_id in counties] color_mapper = LogColorMapper(palette=palette) data = dict( x=county_xs, y=county_ys, name=county_names, rate=county_rates, ) p.grid.grid_line_color = None p.hover.point_policy = "follow_mouse" p.patches('x', 'y', source=data, fill_color={ 'field': 'rate', 'transform': color_mapper }, fill_alpha=0.7, line_color="white", line_width=0.5)
def _log_bokeh_figure(): palette2 = tuple(reversed(pltt)) counties = { code: county for code, county in cnts.items() if county["state"] == "tx" } county_xs = [county["lons"] for county in counties.values()] county_ys = [county["lats"] for county in counties.values()] county_names = [county['name'] for county in counties.values()] county_rates = [unemployment[county_id] for county_id in counties] color_mapper = LogColorMapper(palette=palette2) chart_data = dict( x=county_xs, y=county_ys, name=county_names, rate=county_rates, ) TOOLS = "pan,wheel_zoom,reset,hover,save" p = figure(title="Texas Unemployment, 2009", tools=TOOLS, x_axis_location=None, y_axis_location=None, tooltips=[("Name", "@name"), ("Unemployment rate", "@rate%"), ("(Long, Lat)", "($x, $y)")]) p.grid.grid_line_color = None p.hover.point_policy = "follow_mouse" p.patches('x', 'y', source=chart_data, fill_color={ 'field': 'rate', 'transform': color_mapper }, fill_alpha=0.7, line_color="white", line_width=0.5) # Log bokeh figure as interactive chart in the experiment' artifacts tab. log_chart(name='bokeh_figure', chart=p)
def gen_texas(): from bokeh.io import show from bokeh.models import LogColorMapper from bokeh.palettes import Viridis6 as palette from bokeh.plotting import figure from bokeh.sampledata.us_counties import data as counties from bokeh.sampledata.unemployment import data as unemployment palette.reverse() counties = { code: county for code, county in counties.items() if county["state"] == "tx" } county_xs = [county["lons"] for county in counties.values()] county_ys = [county["lats"] for county in counties.values()] county_names = [county['name'] for county in counties.values()] county_rates = [unemployment[county_id] for county_id in counties] color_mapper = LogColorMapper(palette=palette) data=dict( x=county_xs, y=county_ys, name=county_names, rate=county_rates, ) TOOLS = "pan,wheel_zoom,reset,hover,save" p = figure( title="Texas Unemployment, 2009", tools=TOOLS, x_axis_location=None, y_axis_location=None, tooltips=[ ("Name", "@name"), ("Unemployment rate)", "@rate%"), ("(Long, Lat)", "($x, $y)") ]) p.grid.grid_line_color = None p.hover.point_policy = "follow_mouse" p.patches('x', 'y', source=data, fill_color={'field': 'rate', 'transform': color_mapper}, fill_alpha=0.7, line_color="white", line_width=0.5) show(p)
def add_location_to_dfm(dfm, state="ca"): """ Given dataframe with County field adds county boundaries in order to be used in the plotting routine """ # Build County boundary DataFrame from bokeh county data from bokeh.sampledata.us_counties import data as counties counties = { code: county for code, county in counties.items() if county["state"] == state } county_xs = [county["lons"] for county in counties.values()] county_ys = [county["lats"] for county in counties.values()] county_names = [county['name'] for county in counties.values()] location_df = pd.DataFrame({ 'County': county_names, 'x': county_xs, 'y': county_ys }) return dfm.merge(location_df, on='County', how='left')
def gen_fake_rows(): for year in range(1990, 2031): for county in counties.values(): yield { 'year': year, 'total_population': int(random.random() * 100000), 'energy_use': random.random() * 100000, 'energy_cost': random.random(), 'solar_installed': random.random() * 100000, 'county': county['name'] }
def assignCountyColors(dic, valid=True): EXCLUDED = ("ak", "hi", "pr", "gu", "vi", "mp", "as", "wa", "nv", "ca", "or", "id", "mt", "wy", "ut", "az", "nm", "co", "sd", "nd", "mn", "ne", "ia", "wi", "il", "mi") county_xs = [ np.array(county["lons"]) for county in counties.values() if county['state'] not in EXCLUDED ] county_ys = [ np.array(county["lats"]) for county in counties.values() if county['state'] not in EXCLUDED ] county_names = [ county['name'] for county in counties.values() if county['state'] not in EXCLUDED ] county_damages = [] county_colors = [] for county in counties.values(): if county['state'] in EXCLUDED: continue if not valid: county_damages.append(0) county_colors.append('white') else: try: name = county['name'] state = abbrevstostate[county['state'].upper()] county_damages.append(dic[state][name]) county_colors.append(getCountyColors(dic[state][name])) except: county_damages.append(0) county_colors.append('white') newdf = pd.DataFrame( dict(x=county_xs, y=county_ys, color=county_colors, damages=county_damages, names=county_names)) newdf.fillna(0, inplace=True) return ColumnDataSource(newdf)
def parse_data(source_data, data_start_date, data_end_date): """Parses the previously downloaded data based on the provided fields Args: source_data: the JSON data that was downloaded data_start_date: the first date given in the data data_end_date: the last date given in the data Returns: source: a subset of data that is stored/displayed in the plot dates_source: the full dataset placed into a ColumnDataSource """ global counties county_xs = [county["lons"] for county in counties.values() if county["state"] == "ny"] county_ys = [county["lats"] for county in counties.values() if county["state"] == "ny"] county_names = [county['name'] for county in counties.values() if county["state"] == "ny"] county_new_positives = [int(county['new_positives']) for county in source_data if county['test_date'] == data_end_date] county_cumulative_number_of_positives = [int(county['cumulative_number_of_positives']) for county in source_data if county['test_date'] == data_end_date] county_total_number_of_tests = [int(county['total_number_of_tests']) for county in source_data if county['test_date'] == data_end_date] county_cumulative_number_of_tests = [int(county['cumulative_number_of_tests']) for county in source_data if county['test_date'] == data_end_date] total_data = {} for county in source_data: date = county['test_date'].split("T")[0] if date not in total_data: total_data[date] = [[], [], [], []] total_data[date][0].append(int(county['new_positives'])) total_data[date][1].append(int(county['cumulative_number_of_positives'])) total_data[date][2].append(int(county['total_number_of_tests'])) total_data[date][3].append(int(county['cumulative_number_of_tests'])) data=dict(x=county_xs, y=county_ys, name=county_names, new_positives=county_new_positives, cumulative_number_of_positives=county_cumulative_number_of_positives, total_number_of_tests=county_total_number_of_tests, cumulative_number_of_tests=county_cumulative_number_of_tests) source = ColumnDataSource(data=data ) dates_source = ColumnDataSource(data=total_data) return source, dates_source
heading.append(head) identity.append(ident) origin.append(org) destination.append(dest) groundspeed.append(gs) altitude.append(alt + "00") common_aircraft.append('-') county_count_graph.append('-') #if(state_id!=''): # aircraft[(int(state_id), int(county_id))] = (rate) # destination[(int(state_id), int(county_id))] = (destination1) #print(county_xs) for county in counties.values(): county_xs.append(county["lons"]) county_ys.append(county["lats"]) county_names.append(county['name']) county_rate.append('-') identity.append('-') heading.append('-') altitude.append('-') groundspeed.append('-') origin.append('-') destination.append('-') ##Aircraft counting #Make county list, init county_count and county_count_aircraft_type for county in counties.values(): county_list.append(county['name'])
HoverTool, # hovertool helps the user to hover over the map and give details LogColorMapper # fills the color ) from bokeh.palettes import Viridis6 as palette # imports different palettes from bokeh.plotting import figure # import different figures from bokeh.sampledata.us_counties import data as counties # importing data of counties from bokeh.sampledata.unemployment import data as unemployment # importing data of unemployment within counties palette.reverse() # reverses colors of the palette counties = { code: county for code, county in counties.items() if county["state"] == "nj" } # specify the coude for county state Nj county_xs = [county["lons"] for county in counties.values()] # plotting x axis county_ys = [county["lats"] for county in counties.values()] # plotting y axis county_names = [county['name'] for county in counties.values()] # assigning names of county data county_rates = [unemployment[county_id] for county_id in counties] # assigning unemployment rate of county color_mapper = LogColorMapper(palette=palette) # using the color mapper funtion to fill the map according to the rates source = ColumnDataSource(data=dict( x=county_xs, # assigining x axis y=county_ys, # assigining y axis name=county_names, # naming name rate=county_rates, # naming rate )) TOOLS = "pan,wheel_zoom,reset,hover,save" # tools funtions
def plot_map(pollutant, date, all_pollutants_df): ''' Output a map of all the counties and display the pollutant levels on a specific day ''' from bokeh.sampledata.us_counties import data as counties #The Bokeh counties data has 58 counties listed in CA, but EPA never has all 58 counties #for the pollutants. Here I am copying all the lat/long data for the counties that I have====== #from original BOKEH SAMPLE counties = { code: county for code, county in counties.items() if county["state"] == "ca" } county_xs = [county["lons"] for county in counties.values()] county_ys = [county["lats"] for county in counties.values()] county_names = [county['name'] for county in counties.values()] my_counties = all_pollutants_df[pollutant].columns #Change Log/Lat to use my_counties county_xs_new = [] county_ys_new = [] for c in my_counties: county_xs_new.append(county_xs[county_names.index(c)]) county_ys_new.append(county_ys[county_names.index(c)]) #Plot ========= from bokeh.io import show, export_png # export_png is dependent on selenium. run: # conda install selenium phantomjs pillow from bokeh.models import LinearColorMapper, BasicTicker, ColorBar from bokeh.palettes import Viridis6 as palette from bokeh.plotting import figure color_mapper = LinearColorMapper(palette=palette) data = dict( x=county_xs_new, y=county_ys_new, name=my_counties, rate=list(all_pollutants_df[pollutant].loc[date]), ) TOOLS = "pan,wheel_zoom,reset,hover,save" pollutant_info = { 'co': ['ppm', 'Carbon monoxide'], 'no2': ['ppb', 'Nitrogen dioxide (NO2)'], 'ozone': ['ppm', 'Ozone'], 'pb': ['ug/m3', 'Lead'], 'pm2_5': ['ug/m3', 'PM2.5'], 'pm10': ['ug/m3', 'PM10'], 'so2': ['ppb', 'Sulfur dioxide'] } p = figure(title="California %s, %s" % (pollutant_info[pollutant][1], date), tools=TOOLS, x_axis_location=None, y_axis_location=None, tooltips=[("Name", "@name"), ("%s" % pollutant_info[pollutant][1], "@rate %s" % pollutant_info[pollutant][0]), ("(Long, Lat)", "($x, $y)")]) p.grid.grid_line_color = None p.hover.point_policy = "follow_mouse" p.patches('x', 'y', source=data, fill_color={ 'field': 'rate', 'transform': color_mapper }, fill_alpha=0.7, line_color="white", line_width=0.5) color_bar = ColorBar(color_mapper=color_mapper, ticker=BasicTicker(), label_standoff=12, border_line_color=None, location=(0, 0)) p.add_layout(color_bar, 'right') #export_png(p,'Results/CA_ozone_%s.png'%t.date()) show(p)
def plot_counties(df, variable_to_distribute, variables_to_display, state=None, logcolor=False): """Plots the distribution of a given variable across the given sttate Params ------ df df is a data frame containing the county level data variable_to_distribute variable_to_distribute is the variable that you want to see across the state variables_to_display Variables to display on hovering over each county output: Bokeh plotting object """ from bokeh.sampledata.us_counties import data as counties counties = { code: county for code, county in counties.items() if county["state"] == state.lower() } county_xs = [county["lons"] for county in counties.values()] county_ys = [county["lats"] for county in counties.values()] if variable_to_distribute in variables_to_display: variables_to_display.remove(variable_to_distribute) colors = palettes.RdBu11 #(n_colors) min_value = df[variable_to_distribute].min() max_value = df[variable_to_distribute].max() gran = (max_value - min_value) / float(len(colors)) #print variable_to_distribute,state,min_value,max_value index_range = [min_value + x*gran for x in range(len(colors))] county_colors = [] variable_dictionary = {} variable_dictionary["county_names"] = [county['name'] for county in counties.values()] variable_dictionary["x"] = county_xs variable_dictionary["y"] = county_ys variable_dictionary[re.sub("[^\w]","",variable_to_distribute)] = [] for vd in variables_to_display: variable_dictionary[re.sub("[^\w]","",vd)] = [] for county_id in counties: StateCountyID = str(county_id[0]).zfill(2) + str(county_id[1]).zfill(3) if StateCountyID in list(df["Header-FIPSStandCtyCode"].values): temp_var = df[df["Header-FIPSStandCtyCode"] == StateCountyID][variable_to_distribute].values[0] # if temp_var > 0.0: variable_dictionary[re.sub("[^\w]","",variable_to_distribute)].append(temp_var) for vd in variables_to_display: variable_dictionary[re.sub("[^\w]","",vd)].append(round(float(df[df["Header-FIPSStandCtyCode"] == StateCountyID][vd].values),2)) color_idx = list(temp_var - np.array(index_range)).index(min(x for x in list(temp_var - np.array(index_range)) if x >= 0)) county_colors.append(colors[color_idx]) ''' else: variable_dictionary[re.sub("[^\w]","",variable_to_distribute)].append(0.0) county_colors.append("#A9A9A9") for vd in variables_to_display: variable_dictionary[re.sub("[^\w]","",vd)].append(0.0) ''' else: variable_dictionary[re.sub("[^\w]","",variable_to_distribute)].append(0.0) county_colors.append("#A9A9A9") for vd in variables_to_display: variable_dictionary[re.sub("[^\w]","",vd)].append(0.0) #print temp_var,counties[county_id]["name"] variable_dictionary["color"] = county_colors source = ColumnDataSource(data = variable_dictionary) TOOLS = "pan,wheel_zoom,box_zoom,reset,hover,save" if logcolor: mapper = LogColorMapper(palette=colors, low=min_value, high=max_value) else: mapper = LinearColorMapper(palette=colors, low=min_value, high=max_value) color_bar = ColorBar(color_mapper=mapper, location=(0, 0), orientation='horizontal', title = variable_to_distribute,ticker=FixedTicker(ticks=index_range)) p = figure(title=variable_to_distribute, toolbar_location="left",tools=TOOLS, plot_width=1100, plot_height=700,x_axis_location=None, y_axis_location=None) p.patches('x', 'y', source=source, fill_alpha=0.7,fill_color='color', line_color="#884444", line_width=2) hover = p.select_one(HoverTool) hover.point_policy = "follow_mouse" tool_tips = [("County ", "@county_names")] for key in variable_dictionary.keys(): if key not in ["x","y","color","county_names"]: tool_tips.append((key,"@"+re.sub("[^\w]","",key) + "{1.11}")) hover.tooltips = tool_tips p.add_layout(color_bar, 'below') return p
# External imports import pandas as pd from bokeh.sampledata.us_counties import data as counties # Internal imports from logistics import geocode_addresses from bokeh_chloropleth import bokeh_chloropleth # Washington counties state = "wa" counties = { code: county for code, county in counties.items() if county["state"] == state } county_names = [county['name'] for county in counties.values()] # Read in licensees. licenses = pd.read_excel("./data/active_licenses.xlsx") # Get counties. licenses = licenses licenses["street"] = licenses["address1"] licenses["state"] = licenses["state_code"] licenses["zip"] = licenses["postal_code"] # sample = geocode_addresses(licenses) # Create Bokeh chloropleth from random import randint values = [randint(0, 100) for p in range(0, len(counties))] bokeh_chloropleth(state, values)
with open('noah_data.csv', newline='') as csvfile: next(csvfile) datareader = csv.reader(csvfile) for row in datareader: if float(row[7]) > 0: #only keep wells with positive values data.append(row) #lat = 3, lon = 4, depth = 7 counties = { code: county for code, county in counties.items() if county["state"] == "ca" #Select State } cname = 'Los Angeles' #Name of county county_xs = [ county["lons"] for county in counties.values() if county['name'] == cname ] county_ys = [ county["lats"] for county in counties.values() if county['name'] == cname ] colors = ["#F1EEF6", "#D4B9DA", "#C994C7", "#DF65B0", "#DD1C77", "#980043" ] #we can set colors here for different types, not currently used county_names = [ county['name'] for county in counties.values() if county['name'] == cname ] print(county_names) #This block of code assumes we look at one country a time. Fundamentally we can do more, so this picks out the first one. xc = county_xs[0] yc = county_ys[0] x_well = [float(well[4]) for well in data] #pulls out longitude of wells
def make_map_plot(counties=counties, data=unemployment, year=2018, additional_data=True): # examples directory: http://bokeh.pydata.org/en/latest/docs/gallery/ # example adapted from http://bokeh.pydata.org/en/latest/docs/gallery/texas.html # changes color pallete assignments #palette.reverse() # grab polygons for Colorado counties only counties = { code: county for code, county in counties.items() if county["state"] == "co" } if additional_data: df = build_simple_model_df(save=False) #df = pd.read_parquet('data/processed_data/simple_modeling_set.parquet', engine='fastparquet') counties_df = pd.DataFrame.from_records(counties).T additional_data_df = pd.merge(df, counties_df, how='left', left_on='county', right_on='name') # subset to 2018 additional_data_df = additional_data_df[additional_data_df['year'] == year] # need to convert to this format for Bokeh to render the plot county_xs = [county["lons"] for county in counties.values()] county_ys = [county["lats"] for county in counties.values()] county_names = [county['name'] for county in counties.values()] # This is what we will need to change to adapt the map to use different values # county_rates = [data[county_id] for county_id in counties] county_rates = additional_data_df['unemprate'] expected_consumers = additional_data_df['total_expected_consumers'] / 1000 # maps colors to the color_mapper = LogColorMapper(palette=palette) # Bokeh expects the data in a dict as follows data = dict( x=county_xs, y=county_ys, name=county_names, rate=county_rates, customers=expected_consumers, ) # all tools here: https://bokeh.pydata.org/en/latest/docs/user_guide/tools.html TOOLS = "pan,wheel_zoom,reset,hover,save" p = figure( # title="Colorado Unemployment, 2009", tools=TOOLS, title=f"Colorado County Statistics {str(year)}", tools=TOOLS, # sizing_mode controls how the plot responds to browser resizing sizing_mode="stretch_both", # if you are having issues with the image fitting in the plot box, # you may want to adjust the width policy value width_policy="fit", # We don't need axes for this plot x_axis_location=None, y_axis_location=None, # This is the fun stuff! And so easy to implement, what do we want # the chart to show on hover? tooltips=[("Name", "@name"), ("Unemployment rate", "@rate%"), ("Expected Customers (k)", "@customers"), ("(Long, Lat)", "($x, $y)")]) # A grid isn't going to make this easier to read, turn off p.grid.grid_line_color = None p.hover.point_policy = "follow_mouse" # MUST set to maintain aspect ratio of state p.match_aspect = True # patches is how polygons are passed for visualization p.patches('x', 'y', source=data, fill_color={ 'field': 'customers', 'transform': color_mapper }, fill_alpha=0.7, line_color="white", line_width=0.5) return p
from bokeh.io import show from bokeh.models import ColumnDataSource, HoverTool, LogColorMapper from bokeh.palettes import Viridis6 as palette from bokeh.plotting import figure from bokeh.sampledata.us_counties import data as counties from bokeh.sampledata.unemployment import data as unemployment palette.reverse() counties = {code: county for code, county in counties.items() if county["state"] == "tx"} county_xs = [county["lons"] for county in counties.values()] county_ys = [county["lats"] for county in counties.values()] county_names = [county["name"] for county in counties.values()] county_rates = [unemployment[county_id] for county_id in counties] color_mapper = LogColorMapper(palette=palette) source = ColumnDataSource(data=dict(x=county_xs, y=county_ys, name=county_names, rate=county_rates)) TOOLS = "pan,wheel_zoom,box_zoom,reset,hover,save" p = figure(title="Texas Unemployment, 2009", tools=TOOLS, x_axis_location=None, y_axis_location=None) p.grid.grid_line_color = None p.patches( "x", "y", source=source, fill_color={"field": "rate", "transform": color_mapper},
from bokeh.io import show from bokeh.models import (ColumnDataSource, HoverTool, LogColorMapper) from bokeh.palettes import Viridis6 as palette from bokeh.plotting import figure from bokeh.sampledata.us_counties import data as counties from bokeh.sampledata.unemployment import data as unemployment #palette.reverse() counties = { code: county for code, county in counties.items() if county["state"] == "tx" } county_xs = [county['lons'] for county in counties.values()] county_ys = [county['lats'] for county in counties.values()] county_names = [county['name'] for county in counties.values()] county_rates = [unemployment[county_id] for county_id in counties] color_mapper = LogColorMapper(palette=palette) source = ColumnDataSource( data=dict(x=county_xs, y=county_ys, name=county_names, rate=county_rates)) TOOLS = "pan,wheel_zoom, reset, hover, save" p = figure(title="Texas Unemployment, 2021", tools=TOOLS, x_axis_location=None, y_axis_location=None)
############################################################################ # # Data Prep # ############################################################################ # get built-in data bokeh.sampledata.download() #limit by state !!! order changes with re-run of this script !!! counties = { code: county for code, county in counties.items() if county["state"] == "va" } # end !!! county_x = [county["lons"] for county in counties.values()] county_y = [county["lats"] for county in counties.values()] county_names = [county['name'] for county in counties.values()] ### experimental locs = pd.DataFrame(county_names) locs['x'] = county_x locs['y'] = county_y locs['name'] = locs[0] del locs[0] #delete bedford city as county equivalent and make location data frame bedford_x = [-79.5436,-79.54339,-79.54295,-79.5434,-79.54201,-79.54353,-79.55541,-79.55612,-79.54206,-79.54129,-79.53956,-79.53926,-79.53926,-79.53683,-79.52744,-79.51268,-79.49368,-79.48793,-79.49904,-79.50356,-79.51611,-79.52537,-79.53285,-79.53989,-79.54553,-79.54386] for i in range(0, len(locs.x)): if locs.x[i][0] == bedford_x[0]:
def map(): from bokeh.sampledata.us_counties import data as counties from bokeh.sampledata.unemployment import data as unemployment palette.reverse() counties = { code: county for code, county in counties.items() if county["state"] == "tx" } county_xs = [county["lons"] for county in counties.values()] county_ys = [county["lats"] for county in counties.values()] county_names = [county['name'] for county in counties.values()] county_rates = [unemployment[county_id] for county_id in counties] color_mapper = LogColorMapper(palette=palette) source = ColumnDataSource(data=dict( x=county_xs, y=county_ys, name=county_names, rate=county_rates, )) TOOLS = "pan,wheel_zoom,reset,hover,save" p = figure(title="Texas Unemployment, 2009", tools=TOOLS, x_axis_location=None, y_axis_location=None) p.grid.grid_line_color = None p.patches('x', 'y', source=source, fill_color={ 'field': 'rate', 'transform': color_mapper }, fill_alpha=0.7, line_color="white", line_width=0.5) hover = p.select_one(HoverTool) hover.point_policy = "follow_mouse" hover.tooltips = [ ("Name", "@name"), ("Unemployment rate)", "@rate%"), ("(Long, Lat)", "($x, $y)"), ] #show(p) # grab the static resources js_resources = INLINE.render_js() css_resources = INLINE.render_css() # render template script, div = components(p) html = render_template( 'index.html', plot_script=script, plot_div=div, js_resources=js_resources, css_resources=css_resources, ) return encode_utf8(html)
from bokeh.io import show from bokeh.models import (ColumnDataSource, HoverTool, LogColorMapper) from bokeh.palettes import Viridis6 as palette from bokeh.plotting import figure from bokeh.sampledata.us_counties import data as counties from bokeh.sampledata.unemployment import data as unemployment if __name__ == "__main__": palette.reverse() counties = {code: county \ for code, county in counties.items() \ if county["state"] == "tx" } county_xs = [county["lons"] for county in counties.values()] county_ys = [county["lats"] for county in counties.values()] county_names = [county['name'] for county in counties.values()] county_rates = [unemployment[county_id] for county_id in counties] color_mapper = LogColorMapper(palette=palette) source = ColumnDataSource(data=dict( x=county_xs, y=county_ys, name=county_names, rate=county_rates)) p = figure(title="Texas Unemployment, 2009", tools="pan,wheel_zoom,reset,hover,save", x_axis_location=None, y_axis_location=None) p.grid.grid_line_color = None
def build_state_plot(): from bokeh.sampledata.us_counties import data as counties print('building data sets...') alum_points = create_dictionary_data('./local/alum_lat_lon.csv') cm_points = create_dictionary_data('./local/cm_lat_lon.csv') school_points = create_dictionary_data('./local/school_lat_lon.csv') supporter_points = create_dictionary_data('./local/supporters_lat_lon.csv') print('school data...') cm_data, cm_counties = open_cm_data() for cm in cm_data: students, county = int(cm['num']), cm['county'] cm_counties[county]['num'] += students cm_counties[county]['cms'] += 1 print('creating county info...') counties = { code: county for code, county in counties.items() if (county['state'] == 'ms' or county['state'] == 'ar') } student_numbers = [] for code in counties.keys(): if counties[code]['name'].replace( ' County', '') in cm_counties.keys() and cm_counties.get( counties[code]['name'], { 'state': '' }).get('state', '') == counties[code]['state']: counties[code]['students'] = cm_counties[counties[code] ['name']].get('num', 0) student_numbers.append(cm_counties[counties[code]['name']].get( 'num', 0)) counties[code]['cms'] = cm_counties[counties[code]['name']].get( 'cms', 0) else: counties[code]['students'] = 0 counties[code]['cms'] = 0 max_students = max(student_numbers) print('building plot...') output_file('./map.html') county_xs = [county["lons"] for county in counties.values()] county_ys = [county["lats"] for county in counties.values()] county_names = [ '{} County'.format(county['name']) for county in counties.values() ] county_place = [bool(county['students']) for county in counties.values()] county_students = [ '{} students'.format(county['students']) for county in counties.values() ] county_cms = [ '{} Corps Members'.format(county['cms']) for county in counties.values() ] palette = [CUSTOM_COLORS['Dark Blue'], CUSTOM_COLORS['Teal']] color_mapper = LogColorMapper(palette=palette) source = ColumnDataSource(data=dict(x=county_xs, y=county_ys, county=county_names, has_cm=county_place, students=county_students)) TOOLS = "pan,wheel_zoom,reset,save" p = figure(tools=TOOLS, active_drag="pan", active_scroll=None, active_tap=None, active_inspect=None, x_axis_location=None, y_axis_location=None, toolbar_location="left") p.grid.grid_line_color = None p.sizing_mode = 'scale_width' # p.sizing_mode = 'scale_height' p.patches('x', 'y', source=source, fill_color={ 'field': 'has_cm', 'transform': color_mapper }, fill_alpha=1, line_color="white", line_width=2) # school data points source = ColumnDataSource( dict( x=school_points['lon'], y=school_points['lat'], city=school_points['city'], name=school_points['name'], type=school_points['type'], cms=school_points['number'], )) g = p.square(x="x", y="y", source=source, size=8, color=CUSTOM_COLORS['Purple'], alpha=1, legend='Schools') hover1 = HoverTool(renderers=[g], tooltips=[ ("School Name", "@name"), ("Location", "@city"), ("Type of Partner", "@type"), ("Number of CMs", "@cms"), ]) p.add_tools(hover1) # donor data points source = ColumnDataSource( dict( x=supporter_points['lon'], y=supporter_points['lat'], city=supporter_points['city'], name=supporter_points['name'], donate=supporter_points['last_donate'], )) g = p.circle(x="x", y="y", source=source, size=8, color=CUSTOM_COLORS['Blue'], alpha=1, legend='Supporters') hover2 = HoverTool(renderers=[g], tooltips=[ ("Donor Name", "@name"), ("Location", "@city"), ("Latest Donation", "@donate"), ]) p.add_tools(hover2) # alumni data points source = ColumnDataSource( dict( x=alum_points['lon'], y=alum_points['lat'], city=alum_points['city'], name=alum_points['name'], corps=alum_points['corps'], title=alum_points['title'], employer=alum_points['employer'], profession=alum_points['profession'], last_survey=alum_points['last_survey'], nps=alum_points['nps'], )) g = p.circle(x="x", y="y", source=source, size=8, color=CUSTOM_COLORS['Red'], alpha=1, legend='Alumni') hover3 = HoverTool(renderers=[g], tooltips=[ ("Alum Name", "@name"), ("Corps", "@corps"), ("Location", "@city"), ("Title", "@title"), ("Employer", "@employer"), ("profession", "@profession"), ("Last Alum Survey", "@last_survey"), ("Latest NPS", "@nps"), ]) p.add_tools(hover3) # cm data points source = ColumnDataSource( dict( x=cm_points['lon'], y=cm_points['lat'], city=cm_points['city'], name=cm_points['name'], school=cm_points['school'], coach=cm_points['coach'], content=cm_points['content'], num=cm_points['num'], yol=cm_points['yol'], )) g = p.circle(x="x", y="y", source=source, size=8, color=CUSTOM_COLORS['Orange'], alpha=1, legend='Corps Members') hover4 = HoverTool(renderers=[g], tooltips=[ ("CM Name", "@name"), ("Location", "@city"), ("School", "@school"), ("Coach", "@coach"), ("Content", "@content"), ("Number of Students", "@num"), ("Expected Growth", "@yol"), ]) p.add_tools(hover4) p.legend.location = "top_right" p.legend.click_policy = "hide" p.toolbar.active_inspect = [hover2, hover3, hover4] # p.toolbar.active_inspect = [] show(p)