def create_color_mapper(mapper_type, c_min, c_max, cmap="YlGnBu", cmap_res=8, cmap_r=True): """ create the colormapper mapper_type = "log" or "linear" """ # define the color palette palette = brewer[cmap][cmap_res] # reverese the color palette if desired if cmap_r == True: palette = palette[::-1] #Instantiate LogColorMapper that maps numbers in a range, into a sequence of colors. # Create the specified color mapper if mapper_type == "log": color_mapper = LogColorMapper(palette=palette, low=c_min, high=c_max) elif mapper_type == "linear": color_mapper = LinearColorMapper(palette=palette, low=c_min, high=c_max) else: raise ValueError("mapper_type must be specified as either 'log' or 'linear'") # set the nan_color of the color mapper color_mapper.nan_color = "#f0f0f0" return color_mapper
def _addlegend(self): # Add the color bar if 'z_axis_type' in pytplot.data_quants[self.tvar_name].zaxis_opt: if pytplot.data_quants[self.tvar_name].zaxis_opt['z_axis_type'] == 'log': color_mapper = LogColorMapper(palette=self.colors[0], low=self.zmin, high=self.zmax) color_bar = ColorBarSideTitle(color_mapper=color_mapper, ticker=LogTicker(), border_line_color=None, location=(0, 0)) color_bar.formatter = BasicTickFormatter(precision=2) else: color_mapper = LinearColorMapper(palette=self.colors[0], low=self.zmin, high=self.zmax) color_bar = ColorBarSideTitle(color_mapper=color_mapper, ticker=BasicTicker(), border_line_color=None, location=(0, 0)) color_bar.formatter = BasicTickFormatter(precision=4) else: color_mapper = LogColorMapper(palette=self.colors[0], low=self.zmin, high=self.zmax) color_bar = ColorBarSideTitle(color_mapper=color_mapper, ticker=LogTicker(), border_line_color=None, location=(0, 0)) color_bar.formatter = BasicTickFormatter(precision=2) color_bar.width = 10 color_bar.major_label_text_align = 'left' color_bar.label_standoff = 5 color_bar.major_label_text_baseline = 'middle' color_bar.title = pytplot.data_quants[self.tvar_name].zaxis_opt['axis_label'] color_bar.title_text_font_size = str(pytplot.data_quants[self.tvar_name].extras['char_size'])+'pt' color_bar.title_text_font_style = 'bold' color_bar.title_standoff = 20 self.fig.add_layout(color_bar, 'right')
def _create_choropleth_map(source, width=600, height=1000): """ Create a choropleth map with of incidents in Amsterdam-Amstelland. params ------ source: a Bokeh GeoJSONDataSource object containing the data return ------ a Bokeh figure showing the spatial distribution of incidents in over the region """ map_colors = ['#f2f2f2', '#fee5d9', '#fcbba1', '#fc9272', '#fb6a4a', '#de2d26'] color_mapper = LogColorMapper(palette=map_colors) nonselection_color_mapper = LogColorMapper(palette=gray(6)[::-1]) tooltip_info = [("index", "$index"), ("(x,y)", "($x, $y)"), ("#incidents", "@incident_rate"), ("location id", "@location_id")] map_tools = "pan,wheel_zoom,tap,hover,reset" # get google maps API key with open("./Data/googlemapskey.txt") as f: maps_api_key = f.readline() map_options = GMapOptions(lat=52.35, lng=4.9, map_type="roadmap", zoom=11) p = gmap(maps_api_key, map_options,tools=map_tools, plot_width=width, plot_height=height, x_axis_location=None, y_axis_location=None) p.xaxis.visible=False p.yaxis.visible=False # p = figure(title="Spatial distribution of incidents in Amsterdam-Amstelland", # tools=map_tools, x_axis_location=None, y_axis_location=None, # height=height, width=width, tooltips=tooltip_info) # p.x_range = Range1d(4.66, 5.10) # p.y_range = Range1d(52.18, 52.455) # p.grid.grid_line_color = None # p.add_tile(CARTODBPOSITRON) patches = p.patches('xs', 'ys', source=source, fill_color={'field': 'incident_rate', 'transform': color_mapper}, fill_alpha=0.5, line_color="black", line_width=0.3, nonselection_fill_color={'field': 'incident_rate', 'transform': nonselection_color_mapper}) return p, patches
def init_plot(source): """Initializes the plots Args: source: data for the current day that is displayed by the plots initially Returns: p: plot that is graphed patches: reference to the patches for the plot (handle coloring) color_mapper: reference to the colors/maps that are used in the plot """ global palette palette = tuple(palette) color_mapper = LogColorMapper(palette=palette, low = 1) TOOLS = "wheel_zoom,reset,hover,save" p = figure(plot_width=1000, plot_height=800, sizing_mode="stretch_width", title="New York Covid-19 Data", tools=TOOLS, x_axis_location=None, y_axis_location=None, tooltips=[("Name", "@name"), ("New Positives", "@new_positives"), ("Cumulative Number of Positives", "@cumulative_number_of_positives"), ("Total Number of Tests", "@total_number_of_tests"), ("Cumulative Number of Tests", "@cumulative_number_of_tests"),]) p.grid.grid_line_color = None p.hover.point_policy = "follow_mouse" patches = p.patches('x', 'y', source=source, fill_color={'field': 'new_positives', 'transform': color_mapper}, fill_alpha=0.7, line_color="white", line_width=0.5) return p, patches, color_mapper
def viz_zone_stat(input_shapefile,poly,uid): try: os.remove('ndvi_stats.html') except OSError: pass palette.reverse() output_notebook() output_file('ndvi_stats1.html') props = OrderedDict() with fiona.open(input_shapefile, 'r') as polys: for i in polys: prop = OrderedDict() prop[i['properties'].get(uid)] = {} prop[i['properties'].get(uid)].update({ stat : val for stat , val in i['properties'].items()}) props.update(prop) px = [] py = [] for i in poly: x,y = i.exterior.xy x=x.tolist() y=y.tolist() px.append(x) py.append(y) polyID = [] mndvi = [] std_ndvi= [] color_mapper = LogColorMapper(palette=palette) for key in props: polyID.append(props[key][uid]) mndvi.append(props[key]['mean']) std_ndvi.append(props[key]['std']) source = ColumnDataSource(data=OrderedDict( tid=polyID,mndvi=mndvi,stdndvi=std_ndvi,x=px,y=py)) TOOLS = "pan,wheel_zoom,reset,hover,save" TOOLTIPS=[ ((uid), "@tid"), ("Mean NDVI", "@mndvi"), ("Std. NDVI", "@stdndvi")] p = figure(plot_width=500, plot_height=500,title="Zonal Statistics") #p.hover.point_policy = "follow_mouse" "fill color", "$color[hex, swatch]:fill_color" plots = p.patches('x', 'y', source=source, fill_color={'field': 'mndvi', 'transform': color_mapper}, fill_alpha=0.7, line_color="black", line_width=0.5) p.add_tools(HoverTool(tooltips=TOOLTIPS, mode='mouse')) show(p)
def plot_state_data(dataname, data): color_mapper = LogColorMapper(palette=palette) TOOLS = "pan,wheel_zoom,reset,hover,save" p = figure(tools=TOOLS, x_axis_location=None, y_axis_location=None, match_aspect=True, plot_width=800, plot_height=350, tooltips=[("Name", "@name"), ('value', "@value"), ("(Long, Lat)", "($x, $y)")]) p.grid.grid_line_color = None p.hover.point_policy = "follow_mouse" patches = p.patches('x', 'y', source=data, fill_color={ 'field': 'value', 'transform': color_mapper }, fill_alpha=0.7, line_color="white", line_width=0.5) p.title.text = f'{dataname} in {YEAR_TO_PLOT}'.replace('_', ' ').title() # 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') return p, patches
def show_world_map(self): palette_ = tuple(reversed(palette)) with open('geojson/world-geo.json') as f: json_data = json.load(f) color_mapper = LogColorMapper(palette=palette_) country, lon, lat = self.get_coordinates(json_data) df_countries = pd.DataFrame( { "country": country, "lon": lon, "lat": lat }, columns=['country', 'lon', 'lat']) df_tmp = self.df_world[['country', 'confirmed', 'deaths', 'recovered']] df4 = pd.merge(df_countries, df_tmp, how='left', left_on='country', right_on='country') confirmed = df4['confirmed'].values deaths = df4['deaths'].values recovered = df4['recovered'].values countries = df4['country'].values lon = df4['lon'].values lat = df4['lat'].values data = dict(x=lon, y=lat, name=countries, confirmed=confirmed, recovered=recovered, deaths=deaths) TOOLS = "pan,wheel_zoom,reset,hover,save" p = figure(title="Total worldwide COVID-19 cases", x_axis_location=None, y_axis_location=None, tooltips=[("Name", "@name"), ("Confirmed", "@confirmed"), ("Deaths", "@deaths"), ("Recovered", "@recovered")], active_scroll='wheel_zoom', match_aspect=True) p.grid.grid_line_color = None p.hover.point_policy = "follow_mouse" p.patches('x', 'y', source=data, fill_color={ 'field': 'confirmed', 'transform': color_mapper }, fill_alpha=0.7, line_color="white", line_width=0.5) st.bokeh_chart(p)
def make_plot(mapper_type, palette): mapper_opts = dict(palette=palette, low=1, high=1000) if mapper_type == "linear": mapper = LinearColorMapper(**mapper_opts) else: mapper = LogColorMapper(**mapper_opts) p = figure(toolbar_location=None, tools='', title="", x_axis_type=mapper_type, x_range=(1, 1000)) p.title.text = f"{palette} with {mapper_type} mapping" p.circle(x='x', y='y', alpha=0.8, source=source, size=6, fill_color=transform('x', mapper), line_color=None) color_bar = ColorBar(color_mapper=mapper, ticker=p.xaxis.ticker, formatter=p.xaxis.formatter, padding=0) p.add_layout(color_bar, 'below') return p
def make_color_map(palette, n, field, mode="linear"): """ Parameters ---------- palette : bokeh palette n : int field : str mode : 'linear', 'log' or 'categorical', default 'linear' Returns ------- cmap : dict """ if callable(palette): palette = palette(n) else: palette = palette[n] if mode == "linear": mapper = LinearColorMapper(low=0, high=n, palette=palette) elif mode == "log": mapper = LogColorMapper(low=0, high=n, palette=palette) elif mode == "categorical": mapper = CategoricalColorMapper(factors=[str(i) for i in range(n)], palette=palette) else: raise ValueError("Unrecognized mode.") return {"field": field, "transform": mapper}
def make_choropleth_plot(zip_data, freq_dict, weight, palette, start_month="January", width=500, height=500): data = zip_data data[weight] = freq_dict[weight][start_month] source = ColumnDataSource(data) TOOLS = "pan,wheel_zoom,box_zoom,reset,hover,save" title = "{0} Choropleth for {1}".format( "Destination" if weight == "dropoff_frequency" else "Origin", start_month) choropleth = figure(title=title, tools=TOOLS, x_axis_location=None, y_axis_location=None, responsive=True, plot_width=width, plot_height=height, toolbar_location="above", toolbar_sticky=False) choropleth.grid.grid_line_color = "SlateGray" choropleth.grid.grid_line_alpha = .5 choropleth.grid.minor_grid_line_color = "SlateGray" choropleth.grid.minor_grid_line_alpha = .2 freq_max = 0 for freq_list in freq_dict[weight].values(): freq_max = max(freq_list) if max(freq_list) > freq_max else freq_max color_mapper = LogColorMapper(palette=palette, high=freq_max, low=0.0) patches = choropleth.patches('longitude', 'latitude', source=source, fill_color={ 'field': weight, 'transform': color_mapper }, fill_alpha=.9, line_color="black", line_width=.6) color_bar = ColorBar(color_mapper=color_mapper, label_standoff=12, border_line_color=None, location=(0, 0)) choropleth.add_layout(color_bar, 'right') hover = choropleth.select_one(HoverTool) hover.point_policy = "follow_mouse" hover.tooltips = [("Name", "@name"), ("Zipcode", "@zipcode"), ("Borough", "@borough"), (weight.replace("_", " ").title(), "@{0}%".format(weight)), ("(Long, Lat)", "($x.2, $y.2)")] return choropleth, patches
def make_map(src_map, country, type_display): color_mapper = LogColorMapper(palette=palette) TOOLS = "pan,wheel_zoom,reset,hover,save" p = figure( plot_width=1150, plot_height=800, title='World Map', tools=TOOLS, x_axis_location=None, y_axis_location=None, tooltips=[ ("Name", "@name"), ("Mentions", "@rate") # , # ("(Long, Lat)", "($x, $y)") ]) p.grid.grid_line_color = None p.hover.point_policy = "follow_mouse" p.x_range = Range1d(start=-180, end=180) p.y_range = Range1d(start=-90, end=90) p.grid.grid_line_color = None p.patches('x', 'y', source=src_map, fill_color={ 'field': 'rate', 'transform': color_mapper }, fill_alpha=0.7, line_color="white", line_width=0.5) return (p)
def build_plot(tweet_feature): tweet_source = ColumnDataSource(data=dict(x=tweet_feature['x'], y=tweet_feature['y'], text=tweet_feature['text'], url=tweet_feature['url'], color=tweet_feature['color'])) p = figure(plot_width=600, plot_height=600, tools=[HoverTool(tooltips="""<div style="width:300px">@text</div>"""), TapTool()], toolbar_location=None, title='hover to view tweet text, click to view tweet in a pop-up window') tap = p.select(type=TapTool) tap.callback = OpenURL(url='@url') p.axis.visible = False p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None color_mapper=LogColorMapper(palette='Viridis256', low=1, high=max(tweet_feature['popularity'])+1) color_bar=ColorBar(color_mapper=color_mapper, ticker=LogTicker(), label_standoff=6, border_line_color=None, location=(0,0), title="likes") p.circle(x='x', y='y', source=tweet_source, size=8, fill_color='color', line_color='color') p.add_layout(color_bar, 'right') return components(p)
def make_plot(name): source = ColumnDataSource(data=read_bea(name)) color_mapper = LogColorMapper(palette=Viridis6) TOOLS = "pan,wheel_zoom,reset,hover,save" p = figure(plot_height=500, plot_width=700, title=name, tools=TOOLS, active_scroll='wheel_zoom', x_axis_location=None, y_axis_location=None, tooltips=[("Name", "@name"), (name, "@rate"), ("(Long, Lat)", "($x, $y)")]) p.grid.grid_line_color = None p.hover.point_policy = "follow_mouse" p.patches('x', 'y', source=source, fill_color={ 'field': 'rate', 'transform': color_mapper }, fill_alpha=0.7, line_color="white", line_width=0.5) return p, source
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 bokeh_plot_tcc(gpdf, df_city): """REALLY UGLY IMPLEMENTATION. Also slower than folium rasterlayers""" # https://automating-gis-processes.github.io/CSC18/lessons/L5/interactive-map-bokeh.html def getPolyCoords(row, geom, coord_type): """Returns the coordinates ('x' or 'y') of edges of a Polygon exterior""" # Parse the exterior of the coordinate exterior = row[geom].exterior if coord_type == 'x': # Get the x coordinates of the exterior return list( exterior.coords.xy[0] ) elif coord_type == 'y': # Get the y coordinates of the exterior return list( exterior.coords.xy[1] ) # Get the Polygon x and y coordinates gpdf['x'] = gpdf.apply(getPolyCoords, geom='geometry', coord_type='x', axis=1) gpdf['y'] = gpdf.apply(getPolyCoords, geom='geometry', coord_type='y', axis=1) # Make a copy, drop the geometry column and create ColumnDataSource g_df = gpdf.drop('geometry', axis=1).copy() gsource = ColumnDataSource(g_df) # Let's first do some coloring magic that converts the color palet into map numbers (it's okey not to understand) from bokeh.palettes import Greens9 as palette from bokeh.models import LogColorMapper # Create the color mapper color_mapper = LogColorMapper(palette=palette) # Initialize our figure p = figure(title="Travel times with Public transportation to Central Railway station") # Plot grid p.patches('x', 'y', source=gsource, fill_color={'field': 'tcc', 'transform': color_mapper}, # todo - colorfun not workingg fill_alpha=1.0, line_color="black", line_width=0.05) # https://docs.bokeh.org/en/latest/docs/gallery/image.html p = figure(title="Travel times with Public transportation to Central Railway station") # must give a vector of image data for image parameter # p.image(image=[array], x=0, y=0, dw=10, dh=10, palette=pallette, level="image") # TODO - not sure how to get dw/dh in pixels from the lat/long degrees p.image(image=[array], x=bounds_trans[0], y=bounds_trans[1], dw=10, dh=10, palette=palette, level="image") p.grid.grid_line_width = 0.5 from bokeh.io import output_notebook, show output_notebook() # Not sure why I get runtime errors try: show(p, notebook_handle=True) except RuntimeError: show(p, notebook_handle=True)
def plot_bokeh_intensity_map(self, spatial_entity_to_coordinates, spatial_entity_to_values): entity_xs = [] entity_ys = [] entity_names = [] entity_rates = [] for name, coords in spatial_entity_to_coordinates.items(): xs = [i for i in coords[0]] ys = [i for i in coords[1]] try: intensity_value = np.median(spatial_entity_to_values[name]) except: intensity_value = 0.0 entity_xs.append(xs) entity_ys.append(ys) entity_names.append(name) entity_rates.append(intensity_value) palette.reverse() color_mapper = LogColorMapper(palette=palette) source = ColumnDataSource(data=dict( x=entity_xs, y=entity_ys, name=entity_names, rate=entity_rates, )) TOOLS = "pan,wheel_zoom,reset,hover,save" p = figure(title="London Median House Prices, 2013-2014", 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"), ("Price change rate)", "@rate%"), ("(Long, Lat)", "($x, $y)"), ] show(p)
def create_vertical_color_bar_with_log_cmap(height='auto', width='auto'): color_mapper = LogColorMapper(low=1, high=100000, palette='Viridis256') color_bar = ColorBar(orientation='vertical', color_mapper=color_mapper, height=height, width=width, ticker=LogTicker(), label_standoff=12) return color_bar
def convert_fits2png(self): exp_zfill = str(self.exposure).zfill(8) if self.processing == 'raw': f = '{}/{}/{}/desi-{}.fits.fz'.format(desi_spectro_data, self.night, exp_zfill, exp_zfill) elif self.processing == 'reduced': f = '{}/exposures/{}/{}/sframe-{}-{}.fits'.format( desi_spectro_redux, self.night, exp_zfill, self.cam, exp_zfill) else: return 'Invalid processing option' try: img = fits.open(f) except FileNotFoundError: return 'File not found' if self.processing == 'raw': offset = 0 if self.cam[0] == 'r': offset = 10 if self.cam[0] == 'z': offset = 20 img_data = img[offset + int(self.cam[1]) + 1] low = np.amin(img_data.data) high = np.amax(img_data.data) color_mapper = LogColorMapper(palette="Greys256", low=low, high=high) p = figure(active_drag='box_zoom', height=450, sizing_mode='scale_width', x_range=(0, img_data.data.shape[0] - 1), y_range=(0, img_data.data.shape[1] - 1)) p.image(image=[img_data.data], x=0, y=0, dw=img_data.data.shape[0] - 1, dh=img_data.data.shape[1] - 1, color_mapper=color_mapper) else: img_data = img[1] p = figure(active_drag='box_zoom', height=450, sizing_mode='scale_width', x_range=(0, img_data.data.shape[0] - 1), y_range=(0, img_data.data.shape[1] - 1)) p.image(image=[img_data.data], x=0, y=0, dw=img_data.data.shape[0] - 1, dh=img_data.data.shape[1] - 1, palette="Greys256") return file_html(p, CDN, "png")
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
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 country_geoplot(country_data, shp_path): # TODO: Fix missing countries def load_country_shapes(country_shp_path): #Read shapefile using Geopandas gdf = gpd.read_file(country_shp_path)[['ADMIN', 'ADM0_A3', 'geometry']] #Rename columns gdf.columns = ['country', 'country_code', 'geometry'] gdf = gdf.drop(gdf.index[159]) return gdf def get_geodatasource(gdf): """ Get getjsondatasource from geopandas object """ json_data = json.dumps(json.loads(gdf.to_json())) return GeoJSONDataSource(geojson=json_data) gdf = load_country_shapes(shp_path) plt_cols = ['country', 'confirmed_cases', 'deaths', 'recovered'] plt_df = gdf.merge(country_data[plt_cols], on='country') tile_provider = get_provider(Vendors.CARTODBPOSITRON) geosource = get_geodatasource(plt_df) # color mapping palette = brewer['OrRd'][8] palette = palette[::-1] color_col = 'confirmed_cases' vals = plt_df[color_col] color_mapper = LogColorMapper(palette=palette, low=1, high=vals.max()) tile_provider = get_provider(Vendors.CARTODBPOSITRON) # Tooltip attributes TOOLTIPS = [('Country', '@country'), ('Confirmed cases', '@confirmed_cases'), ('Deaths', '@deaths'), ('Recovered', '@recovered')] p = figure(tooltips=TOOLTIPS, plot_height=400, plot_width=850, match_aspect=True) p.add_tile(tile_provider) # Plot country shapes p.patches('xs', 'ys', source=geosource, fill_alpha=1, line_width=0.5, line_color='black', fill_color={ 'field': color_col, 'transform': color_mapper }) return p
def show_us_map(self): palette_ = tuple(reversed(palette)) with open('geojson/world-geo.json') as f: json_data = json.load(f) color_mapper = LogColorMapper(palette=palette_) states_geo = self.get_geojson() states, lons, lats = self.get_coordinates(states_geo) states_geo = pd.DataFrame({ 'state': states, 'lons': lons, 'lats': lats }) states_df = pd.merge(states_geo, self.latest_states, left_on='state', right_on='state') states_df.set_index('state', inplace=True) cases = states_df['cases'].values deaths = states_df['deaths'].values death_pct = [x / y * 100 for x, y in zip(deaths, cases)] data = dict(x=lons, y=lats, name=states, cases=cases, deaths=deaths, pct=death_pct) TOOLS = "pan,wheel_zoom,reset,hover,save" p = figure(title="Total US COVID-19 cases", x_axis_location=None, y_axis_location=None, tooltips=[("Name", "@name"), ("Cases", "@cases"), ("Deaths", "@deaths"), ("Percentage", "@pct%")], active_scroll='wheel_zoom', match_aspect=True) p.grid.grid_line_color = None p.hover.point_policy = "follow_mouse" p.patches('x', 'y', source=data, fill_color={ 'field': 'cases', 'transform': color_mapper }, fill_alpha=0.7, line_color="white", line_width=0.5) st.bokeh_chart(p)
def dropdownC_handler4(new): temp = dictionary[new.item] dict['c4'] = new.item colorlist = [colors[int((i / max(temp)) * 10)] for i in temp] dictionary['ColorList4'] = colorlist ds4.data = dictionary update_tooltip() mapper = LogColorMapper(palette="Turbo256", low=min(dictionary[new.item]), high=max(dictionary[new.item])) color_bar4.color_mapper = mapper
def mat(self, output_name, nodesX, nodesY, counts): xname = [] yname = [] for node1 in nodesX: for node2 in nodesY: xname.append(node1) yname.append(node2) source = ColumnDataSource(data=dict( xnames=xname, ynames=yname, count=counts.flatten(), )) colors = ["#FFFFFF", "#CCCCFF", "#9999FF", "#5555FF", "#0000FF", "#0000CC", "#0000AA", "#000088", "#000000"] exp_cmap = LogColorMapper(palette=colors, low = 0, high = 10) # exp_cmap = LogColorMapper(palette=colors, low = np.min(counts), high = np.max(counts)) p = figure(title="Matrix Figure", x_axis_location="above", tools="hover,save", x_range=nodesX, y_range=list(reversed(nodesY))) p.rect(x='xnames', y='ynames', width=0.9, height=0.9, source=source, line_color=None, fill_color=transform('count', exp_cmap)) p.plot_width = 800 p.plot_height = 800 p.grid.grid_line_color = None p.axis.axis_line_color = None p.axis.major_tick_line_color = None p.axis.major_label_text_font_size = "5pt" p.axis.major_label_standoff = 0 p.xaxis.major_label_orientation = np.pi / 3 #圖例 color_bar = ColorBar(color_mapper=exp_cmap, location=(0, 0), ticker=BasicTicker(desired_num_ticks=len(colors)), formatter=PrintfTickFormatter(format="%d")) p.add_layout(color_bar, 'right') #游標所指“點”的說明格式 p.select_one(HoverTool).tooltips = [ ('names', '@ynames -> @xnames'), ('count', '@count'), ] output_file(output_name + ".html", title=output_name) show(p) # show the plot
def make_map(d, map_width): rev_dict = {} path = '/Users/a6002538/Downloads/results-20190429-111727.csv' with open(path, 'r') as read_obj: reader = csv.DictReader(read_obj) for row in reader: rev_dict[row['fips']] = float(row['rev_weighted']) for key in rev_dict.keys(): if rev_dict[key] > 1: print(key) p = figure(title='Dollars Spent Per Person', width=map_width, height=int(round(4 / 5 * map_width))) palette = Blues8 palette.reverse() #color_mapper = LinearColorMapper(palette=palette) color_mapper = LogColorMapper(palette=palette) color_mapper.nan_color = 'gray' _data = [] for key in d.keys(): _data.append((rev_dict.get(key, 0), d[key]['x'], d[key]['y'])) _data = sorted(_data) data = [x[0] for x in _data] xs = [x[1] for x in _data] ys = [x[2] for x in _data] #legends = make_legends(data, palette) #fill_colors, legends = log_mapper(data, palette) fill_colors, legends = linear_mapper(data, palette) source = ColumnDataSource(data=dict( x=xs, y=ys, data=data, legend=legends, fill_colors=fill_colors)) p.patches('x', 'y', source=source, fill_color='fill_colors', fill_alpha=0.7, line_color='black', line_width=.2, legend='legend') p.legend.location = "bottom_right" return p
def hot_map_init(self, width=700, height=700, webgl=True): self.districts = NYCGeoPolygon.load_districts() rates = [] for district in self.districts: x, y = district.xy() self.districts_xs.append(x) self.districts_ys.append(y) self.districts_names.append(district.name) rates.append( self.data.pickups[district.index]) # default uses pickups self.hot_map_source = ColumnDataSource(data=dict( x=self.districts_xs, y=self.districts_ys, name=self.districts_names, rate=rates, )) palette.reverse() color_mapper = LogColorMapper(palette=palette) self.hot_map = figure(webgl=webgl, plot_height=height, plot_width=width, tools='pan,wheel_zoom,box_zoom,reset,hover,save', x_axis_location=None, y_axis_location=None) self.hot_map.grid.grid_line_color = None self.hot_map.patches('x', 'y', source=self.hot_map_source, fill_color={ 'field': 'rate', 'transform': color_mapper }, fill_alpha=0.7, line_color="white", line_width=0.5) self.hot_map.title.text = "%s %s/%s, %s" % \ (self.selected_type, self.selected_year, self.selected_month, NYCBorough.BOROUGHS[self.selected_borough]) hover = self.hot_map.select_one(HoverTool) hover.point_policy = "follow_mouse" hover.tooltips = [ ("District", "@name"), ("Trips", "@rate"), ("Coordinates", "($x, $y)"), ]
def plot_map(ds, palette=cts.MAP_PALLETE, breeze=cfg.MAP_BREEZE): """Plot cases map.""" # Calculating map bounds minx, miny, maxx, maxy = ds.total_bounds x_range = maxx - minx y_range = maxy - miny ar = (maxx - minx) / (maxy - miny) x_range = (minx - breeze * x_range, maxx + breeze * x_range) y_range = (miny - breeze * y_range, maxy + breeze * y_range) # Preparing data ds = GeoJSONDataSource(geojson=ds.to_json()) tools = "pan,reset,save" color_mapper = LogColorMapper(palette=tuple(reversed(palette))) p = figure(tools=tools, x_range=x_range, y_range=y_range, aspect_ratio=ar, x_axis_location=None, y_axis_location=None, match_aspect=True) p.grid.grid_line_color = None p.toolbar.logo = None p.patches('xs', 'ys', fill_alpha=0.7, fill_color={ 'field': 'total_color', 'transform': color_mapper }, line_color='gray', line_width=0.25, source=ds) p.add_tools( HoverTool(tooltips=cts.MAP_TOOLTIP, point_policy="follow_mouse", toggleable=False)) # Adding zoom tool wheel_zoom = WheelZoomTool(zoom_on_axis=False) p.add_tools(wheel_zoom) p.toolbar.active_scroll = wheel_zoom # Applying theme doc = curdoc() doc.theme = cfg.THEME return p
def update_colorbar(selectedAgegroups, selectedMeasure): df_selected = df.loc[:, ( df.columns.isin(['AGEGROUP', 'Time', selectedMeasure, 'NAME']))] df_selected = df_selected[df_selected.AGEGROUP.isin( selectedAgegroups)].copy() df_selected = df_selected.groupby(['Time', 'NAME'], sort=False).sum() a, b = df_selected.iloc[:, 0].min(), df_selected.iloc[:, 0].max() # If total below 250, use linear colormapper if (b - a < 250): try: if (b - a < 8): color_bar.color_mapper = LinearColorMapper(palette=palette, low=a, high=a + 8, nan_color='#d9d9d9') color_bar.ticker = BasicTicker(desired_num_ticks=8) else: color_bar.color_mapper = LinearColorMapper(palette=palette, low=a, high=b, nan_color='#d9d9d9') color_bar.ticker = BasicTicker(desired_num_ticks=8) except: color_bar.color_mapper = LinearColorMapper(palette=palette, low=0, high=8, nan_color='#d9d9d9') color_bar.ticker = BasicTicker(desired_num_ticks=8) else: try: color_bar.color_mapper = LogColorMapper(palette=palette, low=a + 1, high=b, nan_color='#d9d9d9') color_bar.ticker = LogTicker(desired_num_ticks=8) except: color_bar.color_mapper = LinearColorMapper(palette=palette, low=0, high=8, nan_color='#d9d9d9') color_bar.ticker = BasicTicker(desired_num_ticks=8) # Adjust the colors used in the map accordingly duh.glyph.fill_color = { 'field': 'Infected_plus', 'transform': color_bar.color_mapper }
def make_map(dataframe, p, data, log=True): new_data = "adja" + data dataframe[new_data] = dataframe[data] + 1e-11 geosource = GeoJSONDataSource(geojson=dataframe.to_json()) # Define color palettes palette = brewer['YlGnBu'][9] palette = palette[:: -1] # reverse order of colors so higher values have darker colors # Instantiate LinearColorMapper that linearly maps numbers in a range, into a sequence of colors. second_smallest = np.partition(dataframe[new_data], -2)[5] third_largest = np.partition(dataframe[new_data], -2)[-5] if log: color_mapper = LogColorMapper(palette=palette, low=second_smallest, high=third_largest) else: color_mapper = LinearColorMapper(palette=palette, low=second_smallest, high=third_largest) # Define custom tick labels for color bar. # Create color bar. color_bar = ColorBar(color_mapper=color_mapper, label_standoff=8, border_line_color=None, location=(0, 0), orientation='horizontal') # Create figure object. p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None # Add patch renderer to figure. states = p.patches('xs', 'ys', source=geosource, fill_color={ 'field': new_data, 'transform': color_mapper }, line_width=0.25, fill_alpha=1) # Create hover tool p.add_tools( HoverTool(renderers=[states], tooltips=[('State', '@STATE_NAME'), (data, '@' + data)])) p.x_range = DataRange1d((-200, -50)) p.add_layout(color_bar, 'below') tab1 = Panel(child=p, title=data) return tab1
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) 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, #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=0.7, line_color="white", line_width=0.5) show(p) script, div = components(p) return script, div