def dashboard(request): state_xs = [state["lons"] for state in states.values()] state_ys = [state["lats"] for state in states.values()] state_names = [state for state in states.keys()] color_mapper = LogColorMapper(palette=palette) rate_dict = {} for name in state_names: rate_dict[name] = 0 rate_values = Lead.objects.values('state').annotate(dcount=Count('state')) for i in rate_values: if i['state'] != None: rate_dict[i['state']] = i['dcount'] print(rate_dict) #rate = [float(random.randrange(1, 10)) for _ in range(0, 51)] rate = list(rate_dict.values()) data = dict( x=state_xs, y=state_ys, name=state_names, rate=rate, ) TOOLS = "pan,wheel_zoom,reset,hover,save" p = figure(title="Number of Leads in Each State", tools=TOOLS, x_axis_location=None, y_axis_location=None, tooltips=[("Name", "@name"), ("Count", "@rate"), ("(Long, Lat)", "($x, $y)")], x_range=(-130, -60), y_range=(20, 60)) p.grid.grid_line_color = None p.hover.point_policy = "follow_mouse" p.legend.location = 'top_right' 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) script, div = components(p) return render(request, 'bokeh/dashboard.html', { 'the_script': script, 'the_div': div })
def create_us_state_map(scores): from bokeh.sampledata.us_states import data as states states = { code: states for code, states in states.items() if code not in ['AK', 'HI'] } state_xs = [state["lons"] for state in states.values()] state_ys = [state["lats"] for state in states.values()] teal_palette = [ '#ffffff', '#e0f2f1', '#b2dfdb', '#80cbc4', '#4db6ac', '#26a69a', '#009688', '#00897b', '#00796b', '#00695c' ] state_names = [state['name'] for state in states.values()] state_scores = [ scores[code] if code in scores.keys() else 0 for code in states.keys() ] color_mapper = LogColorMapper(palette=teal_palette, low=0.01, high=max(scores.values())) data = dict( x=state_xs, y=state_ys, name=state_names, rate=state_scores, ) TOOLS = "pan,wheel_zoom,reset,hover,save" p = figure(title="NLP Ranking Scores Across U.S. States", tools=TOOLS, x_axis_location=None, y_axis_location=None, sizing_mode="scale_width", plot_width=1100, plot_height=700, tooltips=[("State", "@name"), ("Score", "@rate{0,0.00}")]) 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="black", line_width=0.5) return p
["state"] not in ["ak", "hi", "pr", "gu", "vi", "mp", "as"] ] county_colors = [] for county_id in us_counties: if us_counties[county_id]["state"] in [ "ak", "hi", "pr", "gu", "vi", "mp", "as" ]: continue try: rate = unemployment[county_id] idx = min(int(rate / 2), 5) except KeyError: county_colors.append("black") state_names = [state['name'] for state in states.values()] color_mapper = LogColorMapper(palette=palette) source = ColumnDataSource(data=dict(x=state_xs, y=state_ys, name=state_names)) TOOLS = "pan,wheel_zoom,reset,hover,save" """year_slider = Slider(start = 2009, end=2017,value=1,step=1,title="Year") show(widgetbox(year_slider))""" output_file("choropleth.html", title="choropleth.py example") p = figure(title="US Unemployment 2009", tools=TOOLS, toolbar_location="left", plot_width=1100, plot_height=700)
from bokeh.models import HoverTool, HBox, VBox, Slider, Toggle from bokeh.plotting import figure, show, ColumnDataSource from bokeh.sampledata.us_states import data as states from bokeh.palettes import Purples9 states = { code: state for code, state in states.items() if code not in ['HI', 'AK'] } def gen_initial_rate(y): return min(np.random.choice([15, 40]) + np.random.uniform(-10, 10), 100) state_xs = [state['lons'] for state in states.values()] state_ys = [state['lats'] for state in states.values()] colors = Purples9[::-1] names = [state['name'] for state in states.values()] initial_rates = [gen_initial_rate(1) for _ in states.values()] state_colors = [colors[int(rate / 20)] for rate in initial_rates] source = ColumnDataSource(data=dict( x=state_xs, y=state_ys, color=state_colors, name=names, rate=initial_rates)) TOOLS = ['hover'] p = figure(title='Algorithms Deployed, Iteration 0', tools=TOOLS,
from bokeh.plotting import figure, show, ColumnDataSource from bokeh.sampledata.us_states import data as states from bokeh.palettes import Purples9 states = { code: state for code, state in states.items() if code not in ['HI', 'AK'] } def gen_initial_rate(y): return min( np.random.choice([15, 40]) + np.random.uniform(-10, 10), 100 ) state_xs = [state['lons'] for state in states.values()] state_ys = [state['lats'] for state in states.values()] colors = Purples9[::-1] names = [state['name'] for state in states.values()] initial_rates = [gen_initial_rate(1) for _ in states.values()] state_colors = [colors[int(rate / 20)] for rate in initial_rates] source = ColumnDataSource(data=dict( x=state_xs, y=state_ys, color=state_colors, name=names, rate=initial_rates ))
def q3(filedir, outputdir, n_iters=10000): ec = pd.read_csv(filedir + 'electoralCollege.csv') pw = pd.read_csv(filedir + 'probWin.csv') tot = pd.merge(ec, pw, on='State') tot['ProbWin'] = tot['ProbWin'].str.replace('%', "") p1_win = [] p2_win = [] for i in tot['ProbWin']: p1 = float(int(i) / 100) p2 = 1 - p1 p1_win.append(p1) p2_win.append(p2) tot['P1 Win'] = p1_win tot['P2 Win'] = p2_win tot.drop('ProbWin', axis=1) # coerce each column in data frame to a list state_name = list(tot['State']) state_votes = list(tot['Votes']) state_p1_probs = list(tot['P1 Win']) state_p2_probs = list(tot['P2 Win']) # initialize a counter to calculate how many times each party wins p1s_sims = 0 p2s_sims = 0 for x in range(n_iters): p1s = [] p2s = [] for y in range(len(tot)): win = np.random.choice(['p1', 'p2'], p=[p1_win[y], p2_win[y]]) if win == 'p1': p1s.append(tot['Votes'][y]) else: p2s.append(tot['Votes'][y]) if sum(p1s) > 270: p1s_sims += 1 else: p2s_sims += 1 # set up the map boundaries for each state state_xs = [ states[code]["lons"] for code in states if code not in ['HI', 'AK'] ] state_ys = [ states[code]["lats"] for code in states if code not in ['HI', 'AK'] ] # delete outer states in order to keep the map well aligned if 'HI' and 'AK' in states.keys(): del states['HI'] del states['AK'] s = tot.iloc[:, 0].values # set dictionary values for proportions each state votes for winning party props = dict() for j in s: pwin = np.random.choice(['p1', 'p2'], p=[(p1s_sims / n_iters), (p2s_sims / n_iters)]) if (pwin == ['p1']): props[j] = props.get(j, 0) + float( tot.loc[tot['State'] == j]['P1 Win']) else: props[j] = props.get(j, 0) + float( tot.loc[tot['State'] == j]['P2 Win']) data = list(states.values()) final_graph = [] # set up data in the structure of holoviews for x in data: x['Votes'] = tot.loc[tot['State'] == str(x['name'])]['Votes'] x['Party 1'] = str( int( float(tot.loc[tot['State'] == str(x['name'])]['P1 Win']) * 100)) + "%" x['Party 2'] = str( int( float(tot.loc[tot['State'] == str(x['name'])]['P2 Win']) * 100)) + "%" x['Proportions'] = props.get(str(x['name'])) final_graph.append(x) choropleth = hv.Polygons( final_graph, ['lons', 'lats'], [('name', 'State'), ('Votes', 'Votes'), ('Party 1', 'Probability of Party 1 Winning'), ('Party 2', 'Probability of Party 2 Winning'), ('Proportions', 'Proportion Voted for Winning Party')]) ch = choropleth.options(logz=True, tools=['hover'], xaxis=None, yaxis=None, show_grid=False, show_frame=False, width=575, height=400, colorbar=False, line_color='black', color_index='Proportions', cmap="RdBu") hv.save(ch, "jvasanda_hw6_q3.html")
from readData import * data = createJsonObject("crimeData.json") year = 2010 del states["HI"] del states["AK"] state_xs = [states[code]["lons"] for code in states] state_ys = [states[code]["lats"] for code in states] colors = ["#F1EEF6", "#D4B9DA", "#C994C7", "#DF65B0", "#DD1C77", "#980043", "#490303", "#000000"] state_names = [state['name'] for state in states.values()] state_colors = [] state_rates = [] for state_id in states: try: rate = getDataForYear(data, year, state_id) state_rates.append(rate) rate = math.log(rate) idx = int(rate/2) state_colors.append(colors[idx]) except KeyError: state_colors.append("black")
geom = affinity.rotate(geom, 30) f['geometry'] = mapping(geom) return json.dumps(geojson) geojson = get_geojson() [x for x in geojson] from bokeh.models import HoverTool from bokeh.plotting import figure, show, output_file, ColumnDataSource from bokeh.sampledata.us_states import data as states from bokeh.models import LogColorMapper from bokeh.palettes import Viridis6 as palette from bokeh.models import GeoJSONDataSource states.pop('DC') state_xs = [state["lons"] for state in states.values()] state_ys = [state["lats"] for state in states.values()] colors = ["#F1EEF6", "#D4B9DA", "#C994C7", "#DF65B0", "#DD1C77", "#980043"] sorter = pd.DataFrame(columns=['wookie']) for idx, name in enumerate(states): sorter.loc[idx] = [states[name]['name']] final = pd.merge(sorter, final, left_on='wookie', right_on='State').drop('wookie', axis=1) assert [states[name]['name'] for name in states] == final.State.tolist() ############################################################################### from bokeh.sampledata.sample_geojson import geojson state_names = final.State.tolist()
## Choropleth choro = figure(title="Composite Reimbursement by State 2018 (%)", plot_height=575, plot_width=1000, tools=" wheel_zoom, reset, save") EXCLUDED = ("ak", "hi", "pr", "gu", "vi", "mp", "as") state_xs = [states[code]["lons"] for code in states] state_ys = [states[code]["lats"] for code in states] ## Source data state_names = [state['name'] for state in states.values()] state_cc = [state['ccName'] for state in states.values()] state_rates = [state['reimbursement'] for state in states.values()] palette.reverse() color_mapper = LogColorMapper(palette=palette) choro_source = ColumnDataSource(data=dict( x=state_xs, y=state_ys, name=state_names, cost_center=state_cc, rate=state_rates,
def make_dataset(self): per_capita = self.per_capita.active == 1 data_type = self.data_getter.labels[self.data_getter.active].lower() date = self.date.value data = np.empty(len(US_STATES)) if data_type in ("cases", "deaths"): if not per_capita: dt_label = data_type label = f"Total New {data_type.title()}" else: dt_label = f"{data_type}_pc" label = f"New {data_type.title()} per 100,000" subset = GH_STATES_DATA.loc[GH_STATES_DATA["date"] == date, :] for i, (abbrv, state) in enumerate(US_STATES.items()): state_name = state["name"] value = subset.loc[subset["state"] == state_name, f"avg_{dt_label}"] if not value.empty and not np.isnan(value.values[0]): data[i] = max(0, value.values[0]) else: data[i] = 0 maxval = GH_STATES_DATA.loc[:, f"avg_{dt_label}"].max() elif data_type == "positivity": label = "Positivity (%)" subset = TRACKING_DATA.loc[TRACKING_DATA["datetime"] == date, ("state", "positivity")] for i, (abbrv, state) in enumerate(US_STATES.items()): value = subset.loc[subset["state"] == abbrv.upper(), "positivity"] if not value.empty and not np.isnan(value.values[0]): data[i] = max(0, value.values[0]) else: data[i] = 0 maxval = TRACKING_DATA.loc[:, "positivity"].max() interp = ( compute_log_palette # if logarithmic else compute_linear_palette ) color_data = { "color": [interp(PALETTE, maxval / 256, maxval, val) for val in data], "value": data, "state": [state["name"] for state in US_STATES.values()], "lons": [], "lats": [], } for state in US_STATES.values(): color_data["lons"].append(state["lons"]) color_data["lats"].append(state["lats"]) return label, maxval, ColumnDataSource(color_data)
fit = np.polyfit(years, df2.loc[state, dtype], 1) state_data[dtype] = 2018 * fit[0] + fit[1] data_2018[n] = state_data dfs[2018] = pd.DataFrame(data_2018).T df = pd.concat(dfs, names=['year'], sort=False) # Selection box slider_left = Slider(start=2013, end=2018, value=2013, step=1, title='Comparison Year Left') slider_right = Slider(start=2013, end=2018, value=2014, step=1, title='Comparison Year Right') state_xs = [state["lons"] for state in states.values()] state_ys = [state["lats"] for state in states.values()] state_names = [state['name'] for state in states.values()] # get color palletes Blues9.reverse() diffs = RdBu11.copy() diffs_prcp = RdBu11.copy() diffs_prcp.reverse() # diffs.reverse() temp_cmap = LinearColorMapper(palette=RdBu11, low=df['tmax'].min(), high=df['tmax'].max()) diff_cmap = LinearColorMapper(palette=diffs, low=-25, high=25) diff_cmap_prcp = LinearColorMapper(palette=diffs_prcp, low=-25, high=25) prcp_cmap = LinearColorMapper(palette=Blues9, low=0, high=df['prcp'].max()) aqi_cmap = LinearColorMapper(palette=BrBG11, low=df['Median AQI'].min(), high=df['Median AQI'].max())