def __defineMap(self): """define a backgound map tile source""" from bokeh.models import WMTSTileSource url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg' wmts = WMTSTileSource(url=url) mapTiles = gv.WMTS(wmts) return mapTiles
def plot_map(lat, lon, color=None, size=10): center = [lat[0], lon[0]] cmap = cm.rainbow wlat, wlong = latlng_to_meters(lat, lon) colors = [] if color is not None: colors = MinMaxScaler(feature_range=(0, 255)).fit_transform(color) colors = [ "#%02x%02x%02x" % tuple([int(j * 255) for j in cmap(int(i))[:3]]) for i in colors ] wlat0, wlong0 = latlng_to_meters(center[0], center[1]) wlat = np.append(wlat, wlat0) wlong = np.append(wlong, wlong0) colors.append('#010002') openmap_url = 'http://c.tile.openstreetmap.org/{Z}/{X}/{Y}.png' otile_url = 'http://otile1.mqcdn.com/tiles/1.0.0/sat/{Z}/{X}/{Y}.jpg' TILES = WMTSTileSource(url=openmap_url) tools = "pan,wheel_zoom,reset" p = figure(tools=tools, plot_width=700, plot_height=600, x_axis_type="mercator", y_axis_type="mercator") p.circle(wlat0, wlong0, color='#dc3826', size=size + 10) p.circle(np.array(wlat), np.array(wlong), color=colors, size=size, alpha=0.5) p.add_tile(TILES) p.axis.visible = False pb = gridplot([[p]]) show(pb)
def _add_backgroundtile(p, tile_provider, tile_provider_url, tile_attribution, tile_alpha): """Add a background tile to the plot. Either uses predefined Tiles from Bokeh (parameter: tile_provider) or user passed a tile_provider_url of the form '<url>/{Z}/{X}/{Y}*.png' or '<url>/{Z}/{Y}/{X}*.png'.""" from bokeh.models import WMTSTileSource if not tile_provider_url is None: if ("/{Z}/{X}/{Y}" not in tile_provider_url and "/{Z}/{Y}/{X}" not in tile_provider_url): raise ValueError( "<tile_provider_url> has to be of the form '<url>/{Z}/{X}/{Y}*.png' or <url>/{Z}/{Y}/{X}*.png'." ) if not isinstance(tile_attribution, str): raise ValueError("<tile_attribution> has to be a string.") t = p.add_tile( WMTSTileSource(url=tile_provider_url, attribution=tile_attribution)) t.alpha = tile_alpha elif not tile_provider is None: if not isinstance(tile_provider, str): raise ValueError( f"<tile_provider> only accepts the values: {TILE_PROVIDERS}") elif _get_background_tile(tile_provider) != False: t = p.add_tile(_get_background_tile(tile_provider)) else: raise ValueError( f"<tile_provider> only accepts the values: {TILE_PROVIDERS}") t.alpha = tile_alpha return p
def base_map(tile_url, tile_attribution='MapTiler'): # Plot p = figure( title="", plot_width=600, plot_height=700, x_axis_location=None, y_axis_location=None, y_range=(-4300000, 4600000), x_range=(-2450000, 6450000), x_axis_type="mercator", y_axis_type="mercator", ) zoom = WheelZoomTool() p.add_tools(zoom) p.toolbar.active_scroll = zoom drag = PanTool() p.add_tools(drag) p.toolbar.active_drag = drag p.toolbar_location = None p.grid.grid_line_color = None p.add_tile(WMTSTileSource( url=tile_url, attribution=tile_attribution )) return p
def maptiler_plot(key, title, map_type): plot = base_map() protests = load_protests() nations = load_geojson() sum_protests(protests, nations) tile_options = {} tile_options['url'] = key tile_options['attribution'] = 'MapTiler' maptiler = WMTSTileSource(**tile_options) plot.add_tile(maptiler) div = Div(width=400, height=plot.plot_height, height_policy="fixed") point_source = GeoJSONDataSource(geojson=protests.to_json()) location, character, who, why, targets, violence = dropdown() multi_select_loc = one_filter(plot, point_source, "Protest Location", location) multi_select_char = one_filter(plot, point_source, "Characteristics", character) multi_select_who = one_filter(plot, point_source, "Actors Involved", who) multi_select_why = one_filter(plot, point_source, "Causes", why) multi_select_targets = one_filter(plot, point_source, "Targets", targets) multi_select_violence = one_filter(plot, point_source, "Protest violence", violence)#cannot find data if map_type == "patch": patches(plot, div, nations) layout = row(plot, div) return Panel(child=layout, title=title) elif map_type == "point": points(plot, div, point_source, multi_select_loc) layout = row(column(multi_select_loc, multi_select_char, multi_select_who, multi_select_why, multi_select_targets,multi_select_violence), row(plot, div)) return Panel(child=layout, title=title)
def _add_backgroundtile( p, tile_provider, tile_provider_url, tile_attribution, tile_alpha ): """Add a background tile to the plot. Either uses predefined Tiles from Bokeh (parameter: tile_provider) or user passed a tile_provider_url of the form '<url>/{Z}/{X}/{Y}*.png' or '<url>/{Z}/{Y}/{X}*.png'.""" from bokeh.tile_providers import ( CARTODBPOSITRON, CARTODBPOSITRON_RETINA, STAMEN_TERRAIN, STAMEN_TERRAIN_RETINA, STAMEN_TONER, STAMEN_TONER_BACKGROUND, STAMEN_TONER_LABELS, ) from bokeh.models import WMTSTileSource tile_dict = { None: None, "CARTODBPOSITRON": CARTODBPOSITRON, "CARTODBPOSITRON_RETINA": CARTODBPOSITRON_RETINA, "STAMEN_TERRAIN": STAMEN_TERRAIN, "STAMEN_TERRAIN_RETINA": STAMEN_TERRAIN_RETINA, "STAMEN_TONER": STAMEN_TONER, "STAMEN_TONER_BACKGROUND": STAMEN_TONER_BACKGROUND, "STAMEN_TONER_LABELS": STAMEN_TONER_LABELS, } if not tile_provider_url is None: if ( "/{Z}/{X}/{Y}" not in tile_provider_url and "/{Z}/{Y}/{X}" not in tile_provider_url ): raise ValueError( "<tile_provider_url> has to be of the form '<url>/{Z}/{X}/{Y}*.png' or <url>/{Z}/{Y}/{X}*.png'." ) if not isinstance(tile_attribution, str): raise ValueError("<tile_attribution> has to be a string.") t = p.add_tile( WMTSTileSource(url=tile_provider_url, attribution=tile_attribution) ) t.alpha = tile_alpha elif not tile_provider is None: if not isinstance(tile_provider, str): raise ValueError( "<tile_provider> only accepts the values: %s" % tile_dict.keys() ) elif tile_provider.upper() in tile_dict: t = p.add_tile(tile_dict[tile_provider]) else: raise ValueError( "<tile_provider> only accepts the values: %s" % tile_dict.keys() ) t.alpha = tile_alpha return p
def get_provider(self, provider_name): from bokeh.models import WMTSTileSource if isinstance(provider_name, WMTSTileSource): # This allows `get_provider(CARTODBPOSITRON)` to work return WMTSTileSource(url=provider_name.url, attribution=provider_name.attribution) selected_provider = provider_name.upper() if selected_provider not in self.Vendors: raise ValueError('Unknown tile provider %s' % provider_name) url = self._SERVICE_URLS[selected_provider] if selected_provider.startswith('CARTO'): attribution = self._CARTO_ATTRIBUTION elif selected_provider.startswith('STAMEN'): attribution = self._STAMEN_ATTRIBUTION % self._STAMEN_ATTRIBUTION_URLS[ selected_provider] else: raise ValueError('Can not retrieve attribution for %s' % selected_provider) return WMTSTileSource(url=url, attribution=attribution)
def MapPlot(data): def wgs84_to_web_mercator(df, lon="longitude", lat="latitude"): """Converts decimal longitude/latitude to Web Mercator format""" k = 6378137 df["x"] = df[lon] * (k * np.pi / 180.0) df["y"] = np.log(np.tan((90 + df[lat]) * np.pi / 360.0)) * k return df data = wgs84_to_web_mercator(data) x_range = (data['x'].min() - 10000, data['x'].max() + 10000) y_range = (data['y'].min(), data['y'].max()) # convert into ColumnDataSource source = ColumnDataSource(data) mapplot = figure(plot_width=540, plot_height=250, x_range=x_range, y_range=y_range, x_axis_type="mercator", y_axis_type="mercator", toolbar_location=None, tools='', name='geoplot') # credits MAP_URL = 'http://a.basemaps.cartocdn.com/rastertiles/voyager/{Z}/{X}/{Y}.png' attribution = "Tiles by Carto, under CC BY 3.0. Data by OSM, under ODbL" mapplot.add_tile(WMTSTileSource(url=MAP_URL, attribution=attribution)) mapplot.circle(x='x', y='y', fill_color='pink', size=20, fill_alpha=0.3, line_color=None, source=source) # hover mapplot.add_tools( HoverTool( tooltips=[('City', '@city'), ('Latitude', "@latitude"), ('Longitude', "@longitude")])) # others params mapplot.axis.visible = False return mapplot
def get_data(self, element, ranges, style): tile_source = None for url in element.data: if isinstance(url, util.basestring) and not url.endswith('cgi'): try: tile_source = WMTSTileSource(url=url) break except: pass elif isinstance(url, WMTSTileSource): tile_source = url break if tile_source is None: raise SkipRendering("No valid tile source URL found in WMTS " "Element, rendering skipped.") return {}, {'tile_source': tile_source}, style
def test_add_tile_tilesource(): mapnik = xyz.OpenStreetMap.Mapnik tilesource = WMTSTileSource( url=mapnik.build_url(), attribution=mapnik.html_attribution, min_zoom=mapnik.get("min_zoom", 0), max_zoom=mapnik.get("max_zoom", 30), ) plot = figure(x_range=(-2000000, 6000000), y_range=(-1000000, 7000000), x_axis_type="mercator", y_axis_type="mercator") plot.add_tile(tilesource) tile_source = plot.renderers[0].tile_source assert tile_source.url == mapnik.build_url() assert tile_source.attribution == mapnik.html_attribution
def get_plot(data): countries = data.country_name.unique().tolist() countries = [country for country in countries if str(country) != 'nan'] countries.append(' All') countries.sort() p = figure(tools='pan, wheel_zoom, tap, reset', x_range=x_range, y_range=y_range, plot_width=950, toolbar_location="right", active_scroll='wheel_zoom') p.axis.visible = False url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg' attribution = "Tiles by Carto, under CC BY 3.0. Data by OSM, under ODbL" p.add_tile(WMTSTileSource(url=url, attribution=attribution)) source = ColumnDataSource( dict(latitude=latlon.latitude, longitude=latlon.longitude, country_name=latlon.country_name, latitude_t=latlon.latitude, longitude_t=latlon.longitude, country_name_t=latlon.country_name, landslide_size=latlon.landslide_size, source_link=latlon.source_link, location_description=latlon.location_description)) cmap = factor_cmap('landslide_size', palette=[ '#ffffff', '#f7a8e2', '#fcdc12', '#fa774c', '#FC3232', '#040100' ], factors=latlon.landslide_size.unique().tolist()) p.add_tools(HoverTool(tooltips='@location_description', mode='mouse')) url = "@source_link" taptool = p.select(type=TapTool) taptool.callback = OpenURL(url=url) p.circle(x='latitude', y='longitude', fill_color=cmap, size=8, source=source, legend='landslide_size') return (p)
def _add_backgroundtile(p, tile_provider, tile_provider_url): """Add a background tile to the plot. Either uses predefined Tiles from Bokeh (parameter: tile_provider) or user passed a tile_provider_url of the form '<url>/{Z}/{X}/{Y}*.png'.""" from bokeh.tile_providers import ( CARTODBPOSITRON, CARTODBPOSITRON_RETINA, STAMEN_TERRAIN, STAMEN_TERRAIN_RETINA, STAMEN_TONER, STAMEN_TONER_BACKGROUND, STAMEN_TONER_LABELS, ) from bokeh.models import WMTSTileSource tile_dict = { "CARTODBPOSITRON": CARTODBPOSITRON, "CARTODBPOSITRON_RETINA": CARTODBPOSITRON_RETINA, "STAMEN_TERRAIN": STAMEN_TERRAIN, "STAMEN_TERRAIN_RETINA": STAMEN_TERRAIN_RETINA, "STAMEN_TONER": STAMEN_TONER, "STAMEN_TONER_BACKGROUND": STAMEN_TONER_BACKGROUND, "STAMEN_TONER_LABELS": STAMEN_TONER_LABELS, } if not isinstance(tile_provider_url, type(None)): if "/{Z}/{X}/{Y}" not in tile_provider_url: raise ValueError( "<tile_provider_url> has to be of the form '<url>/{Z}/{X}/{Y}*.png'." ) p.add_tile(WMTSTileSource(url=tile_provider_url)) elif not isinstance(tile_provider, type(None)): if not isinstance(tile_provider, str): raise ValueError("<tile_provider> only accepts the values: %s" % tile_dict.keys()) elif tile_provider.upper() in tile_dict: p.add_tile(tile_dict[tile_provider]) else: raise ValueError("<tile_provider> only accepts the values: %s" % tile_dict.keys()) return p
def geographic_overlay(plt, geosourceJson=None, colorBar=None, colorMapper=None, colorMode='', hoverTool=None, mapOverlay=True, enableTapTool=False, enableToolbar=True): if mapOverlay: wmts = WMTSTileSource( url="https://c.tile.openstreetmap.org/{Z}/{X}/{Y}.png") plt.add_tile(wmts) plt.xaxis.axis_label = 'longitude' plt.yaxis.axis_label = 'latitude' plt.xgrid.grid_line_color = None plt.ygrid.grid_line_color = None plt.axis.visible = False plt.patches('xs', 'ys', source=geosourceJson, fill_color={ 'field': colorMode, 'transform': colorMapper }, line_color='purple', line_width=0.5, fill_alpha=0.60 if enableTapTool else 0.65, nonselection_alpha=0.65) plt.add_layout(colorBar, 'right') plt.add_tools(hoverTool) if enableTapTool: plt.add_tools(TapTool()) if enableToolbar: plt.toolbar.autohide = True if plt.title is not None: plt.title.text_font_size = '30pt' return plt
def plot_map(lat, lon, color=None, size=10): cmap = cm.rainbow wlat, wlong = latlng_to_meters(lat, lon) if color is not None: colors = MinMaxScaler(feature_range=(0, 255)).fit_transform(color) colors = [ "#%02x%02x%02x" % tuple([int(j * 255) for j in cmap(int(i))[:3]]) for i in colors ] openmap_url = 'http://c.tile.openstreetmap.org/{Z}/{X}/{Y}.png' otile_url = 'http://otile1.mqcdn.com/tiles/1.0.0/sat/{Z}/{X}/{Y}.jpg' TILES = WMTSTileSource(url=openmap_url) tools = "pan,wheel_zoom,reset" p = figure(tools=tools, plot_width=700, plot_height=600) p.add_tile(TILES) p.circle(np.array(wlat), np.array(wlong), color=colors, size=size) p.axis.visible = False cb = figure(plot_width=130, plot_height=600, tools=tools) yc = np.linspace(np.min(color), np.max(color), 20) c = np.linspace(0, 255, 20).astype(int) dy = yc[1] - yc[0] cb.rect(x=0.5, y=yc, color=[ "#%02x%02x%02x" % tuple([int(j * 255) for j in cmap(int(i))[:3]]) for i in c ], width=1, height=dy) cb.xaxis.visible = False pb = gridplot([[p, cb]]) show(pb)
from bokeh.models import WMTSTileSource from holoviews.operation.datashader import datashade, aggregate, shade shade.cmap = fire hv.extension('bokeh') renderer = hv.renderer('bokeh').instance(mode='server') # Load data ddf = dd.read_parquet(os.path.join(os.path.dirname(__file__),'..','..','..','data','nyc_taxi_wide.parq')).persist() from bokeh.models import WMTSTileSource url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg' wmts = gv.WMTS(WMTSTileSource(url=url)) stream = hv.streams.Stream.define('HourSelect', hour=0)() points = hv.Points(ddf, kdims=['dropoff_x', 'dropoff_y']) dmap = hv.util.Dynamic(points, operation=lambda obj, hour: obj.select(dropoff_hour=hour).relabel('Hour of Day: %d' % hour), streams=[stream]) # Apply aggregation aggregated = aggregate(dmap, link_inputs=True, streams=[hv.streams.RangeXY], width=1200, height=600) # Shade the data class ColormapPicker(hv.streams.Stream): colormap = param.ObjectSelector(default=cm_n["fire"], objects=cm_n.values()) cmap_picker = ColormapPicker(rename={'colormap': 'cmap'}, name='') shaded = shade(aggregated, link_inputs=True, streams=[cmap_picker])
from bokeh.tile_providers import STAMEN_TONER from bokeh.models import WMTSTileSource hv.notebook_extension('bokeh') import param import parambokeh import datashader as ds from holoviews.operation.datashader import datashade from datashader.colors import colormap_select, Greys9, Hot, inferno gv.extension('bokeh') tiles = { 'OpenMap': WMTSTileSource(url='http://c.tile.openstreetmap.org/{Z}/{X}/{Y}.png'), 'ESRI': WMTSTileSource( url= 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg' ), 'Wikipedia': WMTSTileSource( url='https://maps.wikimedia.org/osm-intl/{Z}/{X}/{Y}@2x.png'), 'Stamen Toner': STAMEN_TONER } nyc_taxi = pd.read_csv('data/nyc_taxi.csv', usecols= \ ['pickup_x', 'pickup_y', 'dropoff_x','dropoff_y', 'passenger_count','tpep_pickup_datetime'])
from ipyleaflet import Map from ipywidgets_bokeh import IPyWidget from bokeh.layouts import row from bokeh.models import WMTSTileSource from bokeh.plotting import curdoc, figure center = [51.1079, 17.0385] zoom = 7 map = Map(center=center, zoom=zoom) map_wrapper = IPyWidget(widget=map, width=600, height=400) url = "http://c.tile.openstreetmap.org/{z}/{x}/{y}.png" attribution = "Map data (c) <a href='https://www.openstreetmap.org/'>OpenStreetMap</a> contributors" tile_source = WMTSTileSource(url=url, attribution=attribution) plot = figure( x_range=(1551600, 2212000), y_range=(6417000, 6872000), x_axis_type=None, y_axis_type=None, width=600, height=400, ) plot.add_tile(tile_source) doc = curdoc() doc.add_root(row(map_wrapper, plot))
def make_tracks_figure(doc): """ Create a Bokeh app for visualization of the tracks of hurricanes """ df = pd.read_csv('files/df_full_tracks_bokeh.csv', index_col=0, parse_dates=['Time']) # Remove last entry for each hurricane, add steps numbering, year_start, year_end, zone start df.dropna(subset=['x_end'], inplace=True) df.sort_values(by=['ID', 'Time'], inplace=True) steps = df.groupby(by='ID').Time.count() times = df.groupby(by='ID').Time.first() zones = df.groupby(by='ID').Zones.first() df['Step'] = [i for hur in steps.index for i in range(steps[hur])] df['Year_start'] = [times[hur].year for hur in steps.index for i in range(steps[hur])] df['Month_start'] = [times[hur].month for hur in steps.index for i in range(steps[hur])] df['Zones_start'] = [zones[hur]for hur in steps.index for i in range(steps[hur])] # Convert knots to km/h df['Max_Speed'] = df['Max_Speed'] * 1.852 # ----------------------------------------------------- # FIGURE # ----------------------------------------------------- year_min, year_max, lon_boundaries, lat_boundaries = get_boundaries(df) gulf_stream_lon1, gulf_stream_lon2, gulf_stream_lat1, gulf_stream_lat2 = get_gulf_stream() # credits of the map url = 'http://a.basemaps.cartocdn.com/rastertiles/voyager/{Z}/{X}/{Y}.png' attribution = "Tiles by Carto, under CC BY 3.0. Data by OSM, under ODbL" add_paragraph = additional_legend(loc='spawns') # ----------------------------------------------------- # WIDGETS # ----------------------------------------------------- # definition and configuration of the number selection options_number = ['-1'] + [str(x) for x in list(np.arange(1, 21))] select_number = Select(title='Number of hurricanes:', value='5', options=options_number) # definition and configuration of the zone selection options_zone = ['All', 'Mexico_Caribbean', 'Atlantic'] select_zone = Select(title='Spawning Zone:', value='All', options=options_zone) # definition and configuration of the year and month sliders slider_year = RangeSlider(start=year_min, end=year_max, value=(year_min, year_max), step=1, title="Years") slider_month = RangeSlider(start=1, end=12, value=(1, 12), step=1, title="Months") # definition and configuration of the number selection # select_number_season = Select(title='Number of hurricanes:', value='5', # options=options_number) # definition and configuration of the zone selection # select_zone_season = Select(title='Spawning Zone:', value='All', options=options_zone) # definition and configuration of the year and sliders # slider_year_season = RangeSlider(start=year_min, end=year_max, # value=(year_min, year_max), step=1, title="Years") # definition and configuration of the season selection # options_season = ['All', 'Winter', 'Spring', 'Summer', 'Autumn'] # select_season = Select(title='Season:', value='All', options=options_season) # ------------------------------------------------------- # DATA SOURCE AND RANDOMIZATION # ------------------------------------------------------- np.random.seed(42) n = 5 select_list = list(np.random.choice(df.ID.unique(), size=n, replace=False)) filtr = df.ID.map(lambda x: x in select_list) source = ColumnDataSource(data=df[filtr]) # Initialization of the map p = figure(tools='pan, wheel_zoom', x_range=(lon_boundaries[0], lon_boundaries[1]), y_range=(lat_boundaries[0], lat_boundaries[1]), x_axis_type="mercator", y_axis_type="mercator") p.add_tile(WMTSTileSource(url=url, attribution=attribution)) # Add data points # - Start # - End # - Start with size adjusted to the traveled distance c1 = p.circle(x='x_start', y='y_start', fill_color='green', size=5, source=source) c2 = p.circle(x='x_end', y='y_end', fill_color='green', size=5, source=source) # Line between start and end points s1 = p.segment(x0='x_start', y0='y_start', x1='x_end', y1='y_end', line_dash='dashed', source=source) # Configuration of the hovertool hover = HoverTool(tooltips=[("ID", "@ID"), ("Step", "@Step"), ("Distance", "@Distance")], renderers=[c1]) p.tools.append(hover) # Draw the Gulf Stream p.segment(x0=gulf_stream_lon1[:-1], y0=gulf_stream_lat1[:-1], x1=gulf_stream_lon1[1:], y1=gulf_stream_lat1[1:], legend_label='Gulf Stream', color='red', line_alpha=0.5, line_width=2) p.segment(x0=gulf_stream_lon2[:-1], y0=gulf_stream_lat2[:-1], x1=gulf_stream_lon2[1:], y1=gulf_stream_lat2[1:], color='red', line_alpha=0.5, line_width=2) p.legend.location = "top_left" # DataFrame display no_cols = ['x_start', 'x_end', 'y_start', 'y_end', 'Zones_start', 'ID', 'Time'] cols = ([TableColumn(field='ID', title='ID')] + [TableColumn(field='Time', title='Time', formatter=DateFormatter(format="%d/%m/%Y %H:%M"))] + [TableColumn(field=col, title=col) for col in df.columns if col not in no_cols]) data_table = DataTable(columns=cols, source=source, width=1100, selectable=False) # updating process of the data underlying the map depending on user actions. def update_map_se(attr, old, new): yr = slider_year.value month = slider_month.value zone = select_zone.value n = select_number.value n = int(n) if zone == 'All': df_temp = df.loc[(df['Year_start'] >= yr[0]) & (df['Year_start'] <= yr[1]) & (df['Month_start'] >= month[0]) & (df['Month_start'] <= month[1])] else: df_temp = df.loc[(df.Zones_start == zone) & (df['Year_start'] >= yr[0]) & (df['Year_start'] <= yr[1]) & (df['Month_start'] >= month[0]) & (df['Month_start'] <= month[1])] if n == -1: source.data = ColumnDataSource.from_df(df_temp) else: if n > len(df_temp): # For cases where there are not enough data points n = int(len(df_temp)) np.random.seed(42) select_list = list(np.random.choice(df_temp.ID.unique(), size=n, replace=False)) filtr = df_temp.ID.map(lambda x: x in select_list) source.data = ColumnDataSource.from_df(df_temp.loc[filtr]) # activation of the changes on user action select_number.on_change('value', update_map_se) slider_year.on_change('value', update_map_se) slider_month.on_change('value', update_map_se) select_zone.on_change('value', update_map_se) layout = column(row(column(slider_year, slider_month, select_number, select_zone), p, add_paragraph), data_table) # Make document doc.add_root(layout) doc.title = 'Hurricanes_Tracks' doc.theme = Theme(filename="theme.yaml")
photon,γ,4,2,vb,boson,vector boson,Force carrier,= 0 GeV,0,1,Bose-Einstein,https://mlwild.net/images/photon-gray.svg,https://mlwild.net/images/photon-white.svg Z boson,Z,4,3,vb,boson,vector boson,Force carrier,≃ 91.19 GeV,0,1,Bose-Einstein,https://mlwild.net/images/zboson-gray.svg,https://mlwild.net/images/zboson-white.svg W boson,W,4,4,vb,boson,vector boson,Force carrier,≃80.39 GeV,±1,1,Bose-Einstein,https://mlwild.net/images/wboson-gray.svg,https://mlwild.net/images/wboson-white.svg higgs,H,5,1,sb,boson,scalar boson,Scalar particle,≃124.97 GeV,0,0,Bose-Einstein,https://mlwild.net/images/higgs-gray.svg,https://mlwild.net/images/higgs-white.svg """ from panel.layout.base import WidgetBox from bokeh.plotting import figure from bokeh.models import WMTSTileSource, BBoxTileSource, QUADKEYTileSource p = figure(x_range=(8000000, 16000000), y_range=(000000, 8000000), width=400, height=300, x_axis_type="mercator", y_axis_type="mercator", sizing_mode='stretch_both') p.grid.grid_line_alpha = 0.1 p.toolbar_location = None p.border_fill_color = None p.axis.visible = False p.add_tile(WMTSTileSource(url='https://cartodb-basemaps-4.global.ssl.fastly.net/dark_all/{Z}/{X}/{Y}.png')) import param, pandas as pd from panel.reactive import ReactiveHTML from datetime import date class MaterialTextField(ReactiveHTML): value = param.String(default='') _template = """ <div style="width:400px" id='text_field' class="mdc-text-field mdc-text-field--outlined mdc-text-field--with-leading-icon mdc-text-field--with-trailing-icon"> <i class="material-icons mdc-text-field__icon">favorite</i> <i class="material-icons mdc-text-field__icon">visibility</i> <input class="mdc-text-field__input" id="text-field-hero-input"/>
x_range = Range1d(start=-14000000, end=-7000000, bounds="auto") y_range = Range1d(start=2500000, end=6500000, bounds="auto") fig = Figure(plot_width=1100, plot_height=650, tools=["wheel_zoom", "pan"], x_range=(-13000000, -7000000), y_range=(2750000, 6250000), webgl=True, active_scroll="wheel_zoom") fig.axis.visible = False STAMEN_TONER_BACKGROUND = WMTSTileSource( url='http://tile.stamen.com/toner-background/{Z}/{X}/{Y}.png', attribution= ('Map tiles by <a href="http://stamen.com">Stamen Design</a>, ' 'under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.' 'Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, ' 'under <a href="http://www.openstreetmap.org/copyright">ODbL</a>')) fig.add_tile(STAMEN_TONER_BACKGROUND) accidents.loc[accidents.DRUNK_DR != 0, "DRUNK_DR"] = "YES" accidents.loc[accidents.DRUNK_DR == 0, "DRUNK_DR"] = "NO" accidents.loc[accidents.SP != 0, "SP"] = "YES" accidents.loc[accidents.SP == 0, "SP"] = "NO" accidents.loc[accidents.WEATHER.isin([0, 1, 8, 10, 98, 99]), "WEATHER"] = "Clear" accidents.loc[accidents.WEATHER == 2, "WEATHER"] = "Rain" accidents.loc[accidents.WEATHER == 3, "WEATHER"] = "Sleet/Hail" accidents.loc[accidents.WEATHER == 4, "WEATHER"] = "Snow"
# create plot object title = 'Dynamic Map: National Land Cover Dataset' x_range = Range1d(start=-15473429, end=2108550) y_range = Range1d(start=-6315661, end=7264686) p = Plot(x_range=x_range, y_range=y_range, plot_height=700, plot_width=700, title=title) p.background_fill = "black" p.add_tools(WheelZoomTool(), PanTool()) # add base layer tile_options = {} tile_options['url'] = 'http://tile.stamen.com/toner/{Z}/{X}/{Y}.png' tile_source = WMTSTileSource(**tile_options) p.add_tile(tile_source) # add dynamic data layer # National Land Cover Dataset (http://www.mrlc.gov/nlcd2011.php) service_url = 'http://raster.nationalmap.gov/arcgis/rest/services/LandCover/USGS_EROS_LandCover_NLCD/MapServer/export?' service_url += 'bbox={XMIN},{YMIN},{XMAX},{YMAX}&bboxSR=102100&size={HEIGHT}%2C{WIDTH}&imageSR=102100&format=png32&transparent=true&f=image' image_source_options = {} image_source_options['url'] = service_url image_source = ImageSource(**image_source_options) p.add_dynamic_image(image_source) # create labels layer tile_label_options = {} tile_label_options[ 'url'] = 'http://tile.stamen.com/toner-labels/{Z}/{X}/{Y}.png'
def visualize(self): # Suppress various bokeh warnings warnings.filterwarnings("ignore") flag_list = [] acuteImpacts = AcuteImpacts(targetDir=self.sourceDir, facilityIds=self.facilityIds, parameters=[self.basepath]) flag_df = acuteImpacts.createDataframe() for index, row in flag_df.iterrows(): if row[hq_rel] >= 1.5: flag_list.append((row[fac_id], row.pollutant, "REL")) if row[hq_aegl1] >= 1.5: flag_list.append((row[fac_id], row.pollutant, "AEGL-1 1-hr")) if row[hq_erpg1] >= 1.5: flag_list.append((row[fac_id], row.pollutant, "ERPG-1")) if row[hq_aegl2] >= 1.5: flag_list.append((row[fac_id], row.pollutant, "AEGL-2 1-hr")) if row[hq_erpg2] >= 1.5: flag_list.append((row[fac_id], row.pollutant, "ERPG-2")) flag_list.sort() # If the flag file has no cases of interest, don't do anything. # Otherwise, create a directory for the created acute files. if len(flag_list) == 0: Logger.logMessage( "Acute impacts visualization - " + "No acute impact was greater than or equal to 1.5. No HTML files were generated." ) return else: if os.path.isdir(self.sourceDir + '/Acute Maps') == 0: os.mkdir(self.sourceDir + '/Acute Maps') # Find the HEM dose-response library and create df of it # Under the HEM4 dir names, "Reference" would be "Resources" RefFile = 'resources/Dose_Response_Library.xlsx' RefDF = pd.read_excel(RefFile) RefDF['Pollutant'] = RefDF['Pollutant'].str.lower() RefDF.set_index('Pollutant', inplace=True) RefDict = {'REL': 'REL\n(mg/m3)',\ 'AEGL-1 1-hr':'AEGL-1 (1-hr)\n(mg/m3)',\ 'ERPG-1':'ERPG-1\n(mg/m3)',\ 'AEGL-2 1-hr':'AEGL-2 (1-hr)\n(mg/m3)',\ 'ERPG-2':'ERPG-2\n(mg/m3)',\ 'AEGL-1 8-hr':'AEGL-1 (8-hr)\n(mg/m3)',\ 'AEGL-2 8-hr':'AEGL-2 (8-hr)\n(mg/m3)'} tablist = [] for acuteset in (flag_list): Fac = acuteset[0] HAP = acuteset[1] refType = acuteset[2] path = self.sourceDir + '/' + Fac + '/' HAP = HAP.lower() # Find the all polar file for a given facility, create df of it allpolar = AllPolarReceptors(targetDir=path, facilityId=Fac, acuteyn='Y') allpolar_df = allpolar.createDataframe() allpolar_df[pollutant] = allpolar_df[pollutant].str.lower() # Find the reference value ref_typ_col = RefDict[refType] refVal = RefDF.loc[HAP, ref_typ_col] # Aggregate the all polar file to get HQ for each receptor allpolar_df.set_index('pollutant', inplace=True) HAP_df = allpolar_df.loc[HAP, :] f = {distance: 'first', angle: 'first', aconc: 'sum'} df = HAP_df.groupby([lat, lon], as_index=False).agg(f) df['HQ'] = df[aconc] / refVal / 1000 ac_File = '%s%s%s%s%s' % (self.sourceDir, '/Acute Maps/', Fac + '_', HAP + '_', refType + '.csv') df.to_csv(path_or_buf=ac_File, mode='w+') #Convert df to geo df df['Coordinates'] = list(zip(df.lon, df.lat)) df['Coordinates'] = df['Coordinates'].apply(Point) gdf = gp.GeoDataFrame(df, geometry='Coordinates', crs={'init': 'epsg:4326'}) gdf = gdf.to_crs(epsg=3857) ESRI_tile = WMTSTileSource( url= 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg' ) gdf['x'] = gdf.centroid.map(lambda p: p.x) gdf['y'] = gdf.centroid.map(lambda p: p.y) avg_x = gdf['x'].mean() avg_y = gdf['y'].mean() gdf = gdf.drop('Coordinates', axis=1) gdf['HQ'] = gdf['HQ'].map(lambda x: '%.1g' % x) gdf['lat'] = gdf['lat'].map(lambda x: '%.6f' % x) gdf['lon'] = gdf['lon'].map(lambda x: '%.6f' % x) gdf['angle'] = gdf['angle'].map(lambda x: '%.1f' % x) source = ColumnDataSource(gdf) tooltips = [("Latitude", "@lat"), ("Longitude", "@lon"), ("Acute HQ", "@HQ"), ("Distance (m)", "@distance"), ("Angle (deg)", "@angle")] title = '%s %s Acute HQ (%s)' % (Fac, HAP.title(), refType) tools = [ZoomInTool(), ZoomOutTool(), PanTool(),\ WheelZoomTool(), ResetTool(), HoverTool(tooltips=tooltips)] p = figure(plot_width=800, plot_height=600, tools = tools,\ x_range=(avg_x-3000, avg_x+3000), y_range=(avg_y-3000, avg_y+3000),\ title=title) p.toolbar.active_scroll = p.select_one(WheelZoomTool) p.add_tile(ESRI_tile) p.add_tile(STAMEN_TONER_LABELS) p.circle('x', 'y', color='yellow', size=7, source=source) p.xaxis.visible = False p.yaxis.visible = False p.xgrid.visible = False p.ygrid.visible = False p.background_fill_color = None p.border_fill_color = None # labels = LabelSet(x='x', y='y', text='HQ', source = source,\ # level='glyph', x_offset=0, y_offset=0, text_font_size='8pt',\ # text_color='black', background_fill_color='yellow',\ # text_font_style='bold', text_align='center', text_baseline='middle') labels = LabelSet(x='x', y='y', text='HQ', source = source,\ x_offset=0, y_offset=0, text_font_size='8pt',\ text_color='black', background_fill_color='yellow',\ text_font_style='bold', text_align='center', text_baseline='middle') p.add_layout(labels) curdoc().add_root(p) mapName = '%s%s%s%s%s' % (self.sourceDir, '/Acute Maps/', Fac + '_', HAP + '_', refType + '.html') save(p, filename=mapName) tab = Panel(child=p, title=HAP.title() + " (" + refType + ")") tablist.append(tab) tabs = Tabs(tabs=tablist) curdoc().add_root(tabs) mapName2 = '%s%s%s' % (self.sourceDir, '/Acute Maps/', "All Acute Maps.html") save(tabs, filename=mapName2, title="All Acute HQ Maps") Logger.logMessage( "Acute impacts visualization - HTML files successfully created.")
USA = x_range, y_range = ((-13884029, -7453304), (2698291, 6455972)) p = figure(plot_width=1000, plot_height=700, tools=[my_hover, WheelZoomTool(), 'box_zoom', 'reset'], x_range=x_range, y_range=y_range, toolbar_location="below", x_axis_type="mercator", y_axis_type="mercator") url = 'https://elocation.oracle.com/mapviewer/mcserver/ELOCATION_MERCATOR/osm_positron/{Z}/{Y}/{X}.png' attribution = "© OpenMapTiles © OpenStreetMap contributors" p.add_tile(WMTSTileSource(url=url, attribution=attribution)) # plot1 = p.patches(xs='xs',ys='ys', fill_alpha=0.07,fill_color="grey",line_color = 'black', line_width = 0.25,name= "map",source = contents) p.circle(x='x', y='y', size='sizes', source=source, line_color="color", fill_color="color", fill_alpha=0.05, name="states", legend='range') p.legend.location = "top_left" p.legend.click_policy = "mute"
def on_basemap_change(self, attr, old, new): self.model.basemap = self.model.basemaps[new] self.tile_renderer.tile_source = WMTSTileSource(url=self.model.basemap)
import dask.dataframe as dd import holoviews as hv import geoviews as gv from bokeh.models import WMTSTileSource from holoviews.operation.datashader import datashade url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg' wmts = WMTSTileSource(url=url) # 1. Instead of using hv.extension, declare that we are using Bokeh and grab the renderer renderer = hv.renderer('bokeh') # 2. Declare points and datashade them ddf = dd.read_csv('../data/nyc_taxi.csv', usecols=['pickup_x', 'pickup_y']).persist() shaded = datashade(hv.Points(ddf)) # Set some plot options app = gv.WMTS(wmts) * shaded.opts(plot=dict(width=800, height=600)) # 3. Instead of Jupyter's automatic rich display, render the object as a bokeh document doc = renderer.server_doc(app) doc.title = 'HoloViews Bokeh App'
def make_start_end_figure(doc): """ Creates a Bokeh app for visualizations of start and end of hurricanes """ df_spawn_end = pd.read_csv('files/df_start_end_bokeh.csv', index_col=0) year_min, year_max, lon_boundaries, lat_boundaries = get_boundaries(df_spawn_end) gulf_stream_lon1, gulf_stream_lon2, gulf_stream_lat1, gulf_stream_lat2 = get_gulf_stream() # credits of the map url = 'http://a.basemaps.cartocdn.com/rastertiles/voyager/{Z}/{X}/{Y}.png' attribution = "Tiles by Carto, under CC BY 3.0. Data by OSM, under ODbL" add_paragraph = additional_legend(loc='tracks') # ----------------------------------------------------- # WIDGETS # ----------------------------------------------------- # definition and configuration of the number selection options_number = ['-1'] + [str(x) for x in list(np.arange(1, 21))] select_number = Select(title='Number of hurricanes:', value='5', options=options_number) # definition and configuration of the zone selection options_zone = ['All', 'Mexico_Caribbean', 'Atlantic'] select_zone = Select(title='Spawning Zone:', value='All', options=options_zone) # Definition of buttons for end points and distances toggle_month = Toggle(label="Show end points", button_type="success") toggle_dist_month = Toggle(label="Show distance traveled", button_type="success") # definition and configuration of the year and month sliders slider_year = RangeSlider(start=year_min, end=year_max, value=(year_min, year_max), step=1, title="Years") slider_month = RangeSlider(start=1, end=12, value=(1, 12), step=1, title="Months") # End points toggle_season = Toggle(label="Show end points", button_type="success") toggle_dist_season = Toggle(label="Show distance traveled", button_type="success") # definition and configuration of the number selection select_number_season = Select(title='Number of hurricanes:', value='5', options=options_number) # definition and configuration of the zone selection select_zone_season = Select(title='Spawning Zone:', value='All', options=options_zone) # definition and configuration of the year and sliders slider_year_season = RangeSlider(start=year_min, end=year_max, value=(year_min, year_max), step=1, title="Years") # definition and configuration of the season selection options_season = ['All', 'Winter', 'Spring', 'Summer', 'Autumn'] select_season = Select(title='Season:', value='All', options=options_season) # ------------------------------------------------------- # DATA SOURCE AND RANDOMIZATION # ------------------------------------------------------- np.random.seed(42) n = 5 select_list = list(np.random.choice(df_spawn_end.index, size=n, replace=False)) filtr = df_spawn_end.index.map(lambda x: x in select_list) source = ColumnDataSource(data=df_spawn_end[filtr]) # -------------------------------------------------------- # FIRST TAB # -------------------------------------------------------- # Initialization of the map p = figure(tools='pan, wheel_zoom', x_range=(lon_boundaries[0], lon_boundaries[1]), y_range=(lat_boundaries[0], lat_boundaries[1]), x_axis_type="mercator", y_axis_type="mercator") p.add_tile(WMTSTileSource(url=url, attribution=attribution)) # Add data points # - Start # - End # - Start with size adjusted to the traveled distance c1 = p.circle(x='x_start', y='y_start', fill_color='green', size=8, source=source, legend_label='Start points') c2 = p.circle(x='x_end', y='y_end', fill_color='orange', size=8, source=source, legend_label='End points') d1 = p.circle(x='x_start', y='y_start', fill_color='green', radius='Distance_draw', source=source) # Line between start and end points s1 = p.segment(x0='x_start', y0='y_start', x1='x_end', y1='y_end', line_dash='dashed', source=source) # Initial configuration of WIDGETS for FIRST TAB # - Don't show end points # - Don't show segments between start and end points # - Uniform size for starting points c2.visible, s1.visible, d1.visible = False, False, False # Configuration of the hovertool hover = HoverTool(tooltips=[("ID", "@ID"), ("Duration", "@Duration"), ("Distance", "@Distance")], renderers=[c1, c2, d1], formatters={'Duration': 'printf'}) p.tools.append(hover) # Draw the Gulf Stream p.segment(x0=gulf_stream_lon1[:-1], y0=gulf_stream_lat1[:-1], x1=gulf_stream_lon1[1:], y1=gulf_stream_lat1[1:], legend_label='Gulf Stream', color='red', line_alpha=0.5, line_width=2) p.segment(x0=gulf_stream_lon2[:-1], y0=gulf_stream_lat2[:-1], x1=gulf_stream_lon2[1:], y1=gulf_stream_lat2[1:], color='red', line_alpha=0.5, line_width=2) p.legend.location = "top_left" # DataFrame display no_cols = ['x_start', 'x_end', 'y_start', 'y_end', 'Distance_draw'] cols = [TableColumn(field=col, title=col) for col in df_spawn_end.columns if col not in no_cols] data_table = DataTable(columns=cols, source=source, width=1100, selectable=False) # ------------------------------------------------------------------------ # UPDATING FIRST TAB # ------------------------------------------------------------------------ # updating process of the data underlying the map depending on user actions. def update_map_se(attr, old, new): yr = slider_year.value month = slider_month.value zone = select_zone.value n = select_number.value n = int(n) if zone == 'All': df_temp = df_spawn_end.loc[(df_spawn_end['Year_start'] >= yr[0]) & (df_spawn_end['Year_start'] <= yr[1]) & (df_spawn_end['Month_start'] >= month[0]) & (df_spawn_end['Month_start'] <= month[1])] else: df_temp = df_spawn_end.loc[(df_spawn_end.Zones_start == zone) & (df_spawn_end['Year_start'] >= yr[0]) & (df_spawn_end['Year_start'] <= yr[1]) & (df_spawn_end['Month_start'] >= month[0]) & (df_spawn_end['Month_start'] <= month[1])] if n == -1: source.data = ColumnDataSource.from_df(df_temp) else: if n > len(df_temp): # For cases where there are not enough data points n = int(len(df_temp)) np.random.seed(42) select_list = list(np.random.choice(df_temp.index, size=n, replace=False)) filtr = df_temp.index.map(lambda x: x in select_list) source.data = ColumnDataSource.from_df(df_temp.loc[filtr]) def month_active(atrr, old, new): active = toggle_month.active dist = toggle_dist_month.active if not active: c2.visible, s1.visible = False, False toggle_month.label = "Show end points" else: c2.visible, s1.visible = True, True toggle_month.label= "Unshow end points" if not dist: c1.visible, d1.visible = True, False toggle_dist_month.label = "Show distance traveled" else: c1.visible, d1.visible = False, True toggle_dist_month.label = "Unshow distance traveled" # activation of the changes on user action select_number.on_change('value', update_map_se) slider_year.on_change('value', update_map_se) slider_month.on_change('value', update_map_se) select_zone.on_change('value', update_map_se) toggle_month.on_change('active', month_active) toggle_dist_month.on_change('active', month_active) # Make first tab tab_month = Panel(child=column(row(column(slider_year, slider_month, select_number, select_zone, toggle_month, toggle_dist_month), p, add_paragraph), data_table), title="Monthly") # ---------------------------------------------------------------------------- # SECOND TAB # ---------------------------------------------------------------------------- p_season = figure(tools='pan, wheel_zoom', x_range=(lon_boundaries[0], lon_boundaries[1]), y_range=(lat_boundaries[0], lat_boundaries[1]), x_axis_type="mercator", y_axis_type="mercator") p_season.add_tile(WMTSTileSource(url=url, attribution=attribution)) # Add data points # - Start # - End # - Start with size adjusted to the traveled distance c3 = p_season.circle(x='x_start', y='y_start', fill_color='green', size=8, source=source, legend_label='Start points') c4 = p_season.circle(x='x_end', y='y_end', fill_color='orange', size=8, source=source, legend_label='End points') d2 = p_season.circle(x='x_start', y='y_start', fill_color='green', radius='Distance_draw', source=source) # line between start and end points s2 = p_season.segment(x0='x_start', y0='y_start', x1='x_end', y1='y_end', line_dash='dashed', source=source) # Initial configuration of WIDGETS for SECOND TAB # - Don't show end points # - Don't show segments between start and end points # - Uniform size for starting points c4.visible, s2.visible, d2.visible = False, False, False # Configuration of the hovertool hover_season = HoverTool(tooltips=[("ID", "@ID"), ("Duration", "@Duration"), ("Distance", "@Distance")], renderers=[c3, c4], formatters={'Duration': 'printf'}) p_season.tools.append(hover_season) # Gulf Stream p_season.segment(x0=gulf_stream_lon1[:-1], y0=gulf_stream_lat1[:-1], x1=gulf_stream_lon1[1:], y1=gulf_stream_lat1[1:], legend_label='Gulf Stream', color='red', line_alpha=0.5, line_width=2) p_season.segment(x0=gulf_stream_lon2[:-1], y0=gulf_stream_lat2[:-1], x1=gulf_stream_lon2[1:], y1=gulf_stream_lat2[1:], color='red', line_alpha=0.5, line_width=2) p_season.legend.location = "top_left" # ------------------------------------------------------------------------ # UPDATING SECOND TAB # ------------------------------------------------------------------------ # updating process of the data underlying the map depending on user actions. def update_map_season(attr, old, new): yr = slider_year_season.value season = select_season.value zone = select_zone_season.value n = select_number_season.value n = int(n) if (zone == 'All') & (season == 'All'): df_temp = df_spawn_end.loc[(df_spawn_end['Year_start'] >= yr[0]) & (df_spawn_end['Year_start'] <= yr[1])] elif (zone != 'All') & (season == 'All'): df_temp = df_spawn_end.loc[(df_spawn_end.Zones_start == zone) & (df_spawn_end['Year_start'] >= yr[0]) & (df_spawn_end['Year_start'] <= yr[1])] elif (zone == 'All') & (season != 'All'): df_temp = df_spawn_end.loc[(df_spawn_end.Season_start == season) & (df_spawn_end['Year_start'] >= yr[0]) & (df_spawn_end['Year_start'] <= yr[1])] else: df_temp = df_spawn_end.loc[(df_spawn_end.Zones_start == zone) & (df_spawn_end.Season_start == season) & (df_spawn_end['Year_start'] >= yr[0]) & (df_spawn_end['Year_start'] <= yr[1])] if n == -1: source.data = ColumnDataSource.from_df(df_temp) else: if n > len(df_temp): # For cases where there are not enough data points n = int(len(df_temp)) np.random.seed(42) select_list = list(np.random.choice(df_temp.index, size=n, replace=False)) filtr = df_temp.index.map(lambda x: x in select_list) source.data = ColumnDataSource.from_df(df_temp.loc[filtr]) def season_active(atrr, old, new): active = toggle_season.active dist = toggle_dist_season.active if not active: c4.visible, s2.visible = False, False toggle_season.label = "Show end points" else: c4.visible, s2.visible = True, True toggle_season.label = "Show end points" if not dist: c3.visible, d2.visible = True, False toggle_dist_season.label = "Show distance traveled" else: c3.visible, d2.visible = False, True toggle_dist_season.label = "Unshow distance traveled" select_number_season.on_change('value', update_map_season) slider_year_season.on_change('value', update_map_season) select_season.on_change('value', update_map_season) select_zone_season.on_change('value', update_map_season) toggle_season.on_change('active', season_active) toggle_dist_season.on_change('active', season_active) # Make second tab tab_season = Panel(child=column(row(column(slider_year_season, select_number_season, select_season, select_zone_season,toggle_season, toggle_dist_season), p_season, add_paragraph), data_table), title="Seasonal") # ---------------------------------------------------------------------------- # FINAL SET UP # ---------------------------------------------------------------------------- tabs = Tabs(tabs=[tab_month, tab_season]) def tab_change(atrr, old, new): if tabs.active == 0: update_map_se('', '', '') else: update_map_season('', '', '') tabs.on_change('active', tab_change) # Make document doc.add_root(tabs) doc.title = 'Hurricanes' doc.theme = Theme(filename="theme.yaml")
def create_layout(self): # create figure self.x_range = Range1d(start=self.model.map_extent[0], end=self.model.map_extent[2], bounds=None) self.y_range = Range1d(start=self.model.map_extent[1], end=self.model.map_extent[3], bounds=None) self.fig = Figure(tools='wheel_zoom,pan', x_range=self.x_range, lod_threshold=None, plot_width=self.model.plot_width, plot_height=self.model.plot_height, background_fill_color='black', y_range=self.y_range) self.fig.min_border_top = 0 self.fig.min_border_bottom = 10 self.fig.min_border_left = 0 self.fig.min_border_right = 0 self.fig.axis.visible = False self.fig.xgrid.grid_line_color = None self.fig.ygrid.grid_line_color = None # add tiled basemap self.tile_source = WMTSTileSource(url=self.model.basemap) self.tile_renderer = TileRenderer(tile_source=self.tile_source) self.fig.renderers.append(self.tile_renderer) # add datashader layer self.image_source = ImageSource( url=self.model.service_url, extra_url_vars=self.model.shader_url_vars) self.image_renderer = DynamicImageRenderer( image_source=self.image_source) self.fig.renderers.append(self.image_renderer) # add label layer self.label_source = WMTSTileSource(url=self.model.labels_url) self.label_renderer = TileRenderer(tile_source=self.label_source) self.fig.renderers.append(self.label_renderer) # Add placeholder for legends (temporarily disabled) # self.model.legend_side_vbox = Column() # self.model.legend_bottom_vbox = Column() # add ui components controls = [] axes_select = Select(name='Axes', options=list(self.model.axes.keys())) axes_select.on_change('value', self.on_axes_change) controls.append(axes_select) self.field_select = Select(name='Field', options=list(self.model.fields.keys())) self.field_select.on_change('value', self.on_field_change) controls.append(self.field_select) self.aggregate_select = Select( name='Aggregate', options=list(self.model.aggregate_functions.keys())) self.aggregate_select.on_change('value', self.on_aggregate_change) controls.append(self.aggregate_select) transfer_select = Select(name='Transfer Function', options=list( self.model.transfer_functions.keys())) transfer_select.on_change('value', self.on_transfer_function_change) controls.append(transfer_select) color_ramp_select = Select(name='Color Ramp', options=list(self.model.color_ramps.keys())) color_ramp_select.on_change('value', self.on_color_ramp_change) controls.append(color_ramp_select) spread_size_slider = Slider(title="Spread Size (px)", value=0, start=0, end=10, step=1) spread_size_slider.on_change('value', self.on_spread_size_change) controls.append(spread_size_slider) # hover (temporarily disabled) #hover_size_slider = Slider(title="Hover Size (px)", value=8, start=4, # end=30, step=1) #hover_size_slider.on_change('value', self.on_hover_size_change) #controls.append(hover_size_slider) # legends (temporarily disabled) # controls.append(self.model.legend_side_vbox) # add map components basemap_select = Select(name='Basemap', value='Imagery', options=list(self.model.basemaps.keys())) basemap_select.on_change('value', self.on_basemap_change) image_opacity_slider = Slider(title="Opacity", value=100, start=0, end=100, step=1) image_opacity_slider.on_change('value', self.on_image_opacity_slider_change) basemap_opacity_slider = Slider(title="Basemap Opacity", value=100, start=0, end=100, step=1) basemap_opacity_slider.on_change('value', self.on_basemap_opacity_slider_change) show_labels_chk = CheckboxGroup(labels=["Show Labels"], active=[0]) show_labels_chk.on_click(self.on_labels_change) map_controls = [ basemap_select, basemap_opacity_slider, image_opacity_slider, show_labels_chk ] self.controls = Column(height=600, children=controls) self.map_controls = Row(width=self.fig.plot_width, children=map_controls) # legends (temporarily disabled) self.map_area = Column(width=900, height=600, children=[self.map_controls, self.fig]) self.layout = Row(width=1300, height=600, children=[self.controls, self.map_area]) self.model.fig = self.fig self.model.update_hover()
from bokeh.plotting import figure, ColumnDataSource from bokeh.models import HoverTool, Select, WMTSTileSource, \ LassoSelectTool, Circle, MultiLine, \ Label, TapTool from bokeh.models.widgets import RadioButtonGroup, Slider # pylint: disable-msg=C0103 # WDIR = Path(sys.argv[1]) WDIR = Path("C:\\Users\\riw\\tubCloud\\Uni\\Market_Tool\\pomato\\data_temp\\bokeh_files") STAMEN_LITE = WMTSTileSource( url='http://tile.stamen.com/toner-background/{Z}/{X}/{Y}.png', # url='http://tile.stamen.com/terrain-lines/{Z}/{X}/{Y}.png', # url='https://maps.wikimedia.org/osm-intl/{Z}/{X}/{Y}@2x.png', attribution=( 'Probably cc' )) def init_market_data(market_db): """load data from market_result/market_db forder""" data_dir = WDIR.joinpath("market_result").joinpath(market_db) nodes = pd.read_csv(data_dir.joinpath("nodes.csv"), index_col=0) g_by_fuel = pd.read_csv(data_dir.joinpath("g_by_fuel.csv"), index_col=0) demand = pd.read_csv(data_dir.joinpath("demand.csv"), index_col=0) inj = pd.read_csv(data_dir.joinpath("inj.csv"), index_col=0) f_dc = pd.read_csv(data_dir.joinpath("f_dc.csv"), index_col=0) t_dict = json.load(open(data_dir.joinpath("t.json")))
from bokeh.models import Plot from bokeh.models import Range1d from bokeh.models import WheelZoomTool, ResizeTool, PanTool, BoxZoomTool from bokeh.models import WMTSTileSource output_file("tile_source_example.html", title="Tile Source Example") # set to roughly full extent of web mercator projection x_range = Range1d(start=-20000000, end=20000000) y_range = Range1d(start=-20000000, end=20000000) # create tile source from templated url tile_options = {} tile_options['url'] = 'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png' tile_source = WMTSTileSource(**tile_options) # instantiate plot and add tile source p = Plot(x_range=x_range, y_range=y_range, plot_height=800, plot_width=800) p.add_tools(ResizeTool(), WheelZoomTool(), PanTool(), BoxZoomTool()) tile_renderer_options = {} p.add_tile(tile_source, **tile_renderer_options) doc = Document() doc.add(p) if __name__ == "__main__": filename = "tile_source.html" with open(filename, "w") as f: f.write(file_html(doc, INLINE, "Tile Source Example"))
# Apply datashading to census data x_range, y_range = ((-13884029.0, -7453303.5), (2818291.5, 6335972.0)) # Continental USA shade_defaults = dict(x_range=x_range, y_range=y_range, x_sampling=10, y_sampling=10, width=1200, height=682, color_key=color_key, aggregator=ds.count_cat('race'),) shaded = datashade(census_points, **shade_defaults) shapefile = {'state_house': 'cb_2016_48_sldl_500k', 'state_senate': 'cb_2016_48_sldu_500k', 'us_house': 'cb_2015_us_cd114_5m'} # Define tile source tile_url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg' tiles = gv.WMTS(WMTSTileSource(url=tile_url)) DIVISION_ID_RE = { 'state_house': re.compile(r'ocd-division/country:us/state:[a-z]{2}/sldl:([0-9]+)'), 'state_senate': re.compile(r'ocd-division/country:us/state:[a-z]{2}/sldu:([0-9]+)'), 'us_house': re.compile(r'ocd-division/country:us/state:[a-z]{2}/cd:([0-9]+)'), 'county': re.compile(r'ocd-division/country:us/state:[a-z]{2}/county:[^\/]+/council_district:([0-9]+)'), 'city_council': re.compile(r'ocd-division/country:us/state:[a-z]{2}/place:[^\/]+/council_district:([0-9]+)'), } # engine = create_engine('mysql+mysqlconnector://atxhackathon:atxhackathon@atxhackathon.chs2sgrlmnkn.us-east-1.rds.amazonaws.com:3306/atxhackathon', echo=False) # cnx = engine.raw_connection() # vtd_data = pd.read_sql('SELECT * FROM vtd2016preselection', cnx)