コード例 #1
0
    def test_get_provider(self, name):
        assert name in bt.Vendors
        enum_member = getattr(bt.Vendors, name)
        p1 = bt.get_provider(enum_member)
        p2 = bt.get_provider(name)
        p3 = bt.get_provider(name.lower())
        assert isinstance(p1, WMTSTileSource)
        assert isinstance(p2, WMTSTileSource)
        assert isinstance(p3, WMTSTileSource)
        assert p1 is not p2
        assert p2 is not p3
        assert p1 is not p3
        assert p1.url == p2.url == p3.url
        assert p1.attribution == p2.attribution == p3.attribution

        with pytest.deprecated_call():
            # This will not return a WMTSTileSource in bokeh 2.0.0!
            default_instance = getattr(bt, name)
        new_instance = bt.get_provider(default_instance)
        assert default_instance is not new_instance
        assert default_instance.url == new_instance.url
        assert default_instance.attribution == new_instance.attribution
コード例 #2
0
 def test_attribution(self, name) -> None:
     p = bt.get_provider(getattr(bt, name))
     assert p.attribution == xyz.CartoDB.Positron.html_attribution
コード例 #3
0
ファイル: map.py プロジェクト: cplumejeaud/M2_python
# https://docs.bokeh.org/en/latest/docs/user_guide/geo.html
from bokeh.plotting import figure, output_file, show
from bokeh.tile_providers import CARTODBPOSITRON, get_provider

output_file("tile.html")

tile_provider = get_provider(CARTODBPOSITRON)

# range bounds supplied in web mercator coordinates
# p = figure(x_range=(-2000000, 6000000), y_range=(-1000000, 7000000),
#           x_axis_type="mercator", y_axis_type="mercator")
# 3857 EPSG

# Modify the bounding boxes with those of arctic points
# Using that -86.1200000000000045,-31.2199999999999989 : 30.0,75.5499999999999972
p = figure(x_range=(-9587947, 0),
           y_range=(3503549, 13195489),
           x_axis_type="mercator",
           y_axis_type="mercator")

p.add_tile(tile_provider)

show(p)
コード例 #4
0
def define_segment(local_time):
    f'''
    # Define Segment: {local_time.split()[0]}
    '''
    '''
    $contents
    '''
    '''
    ## Load Data
    
    Open a connection to the database and load the data for a ride containing the segment.
    '''
    s = session('-v2')
    df = Statistics(s, activity_journal=local_time). \
        by_name(SegmentReader, N.SPHERICAL_MERCATOR_X, N.SPHERICAL_MERCATOR_Y, N.DISTANCE, N.ELEVATION,
                N.LATITUDE, N.LONGITUDE).df
    df.dropna(inplace=True)
    df.describe()
    '''
    ### Select Segment

    Use the sliders to isolate the segment.
    
    You may need to play with both sliders before the map displays correctly 
    (todo - fix this, and also all the log messages).  
    '''
    TILE = tile_providers.get_provider(tile_providers.Vendors.STAMEN_TERRAIN)

    output_file(filename='/dev/null')
    width, height = 800, 800

    def modify_doc(doc):

        t1 = PreText(height=20, width=200)
        t2 = PreText(height=20, width=200)
        t3 = PreText(height=20, width=100)
        s1 = Slider(start=0, end=len(df), value=0, title='Start')
        s2 = Slider(start=1, end=len(df) - 1, value=len(df), title='Length')
        map = figure(plot_width=width,
                     plot_height=height,
                     x_axis_type='mercator',
                     y_axis_type='mercator',
                     match_aspect=True)
        map.add_tile(TILE)
        map.circle(x=N.SPHERICAL_MERCATOR_X,
                   y=N.SPHERICAL_MERCATOR_Y,
                   source=df,
                   name='map')
        elevation = figure(plot_width=width, plot_height=height // 10)
        elevation.line(x=N.DISTANCE,
                       y=N.ELEVATION,
                       source=df,
                       name='elevation')
        c = column(row(s1, s2), row(t1, t2, t3), map, elevation)

        def mkplot(l1, l2):
            l2 = min(len(df) - 1, l1 + l2)
            t1.text = '%9.5f,%9.5f' % (df.iloc[l1]['Longitude'],
                                       df.iloc[l1]['Latitude'])
            t2.text = '%9.5f,%9.5f' % (df.iloc[l2]['Longitude'],
                                       df.iloc[l2]['Latitude'])
            t3.text = '%4.2fkm' % (
                (df.iloc[l2]['Distance'] - df.iloc[l1]['Distance']) / 1000)
            get_renderer(map, 'map').data_source.data = df[l1:l2]
            get_renderer(elevation, 'elevation').data_source.data = df[l1:l2]

        s1.on_change('value',
                     lambda attr, old, new: mkplot(s1.value, s2.value))
        s2.on_change('value',
                     lambda attr, old, new: mkplot(s1.value, s2.value))
        doc.add_root(c)

    show(modify_doc)
    '''
    ## Define Segment
    
    Replace the details below with your own from the plot above.
    The start and finish values are (lat, lon); the distance is in metres.
    
    Finally, uncomment the `s.add()` to add this to the database.
    '''

    segment = Segment(
        start=(-70.61813, -33.41536),
        finish=(-70.63340, -33.42655),
        distance=4400,
        name='San Cristobal',
        description='Climb up San Cristobal in Parque Metropolitana')
コード例 #5
0
    height=50)

#sfrom bokeh.tile_providers import CARTODBPOSITRON

map_repr = 'mercator'
# set up/draw the map
p = figure(
    #    x_range=(minlng,maxlng),
    #    y_range=(minlat, maxlat),
    x_axis_type=map_repr,
    y_axis_type=map_repr,
    title='IDLE Vehicles Map',
    match_aspect=True)

#ESRI_IMAGERY,OSM
tile_provider = get_provider(CARTODBPOSITRON)
p.add_tile(tile_provider)

tiles = {
    'Light': get_provider(CARTODBPOSITRON),
    'Open Street': get_provider(OSM),
    'Satellite': get_provider(ESRI_IMAGERY)
}

#select menu


#callback
def change_tiles_callback(attr, old, new):
    #removing the renderer corresponding to the tile layer
    p.renderers = [
コード例 #6
0
from bokeh.io import output_file, show
from bokeh.models import CustomJSHover, HoverTool
from bokeh.plotting import figure
from bokeh.tile_providers import CARTODBPOSITRON, get_provider

output_file("customjs_hover.html")

# range bounds supplied in web mercator coordinates
p = figure(x_range=(-2000000, 6000000),
           y_range=(-1000000, 7000000),
           x_axis_type="mercator",
           y_axis_type="mercator")
p.add_tile(get_provider(CARTODBPOSITRON))

p.circle(x=[0, 2000000, 4000000], y=[4000000, 2000000, 0], size=30)

code = """
    var projections = Bokeh.require("core/util/projections");
    var x = special_vars.x
    var y = special_vars.y
    var coords = projections.wgs84_mercator.invert(x, y)
    return coords[%d].toFixed(2)
"""

p.add_tools(
    HoverTool(tooltips=[
        ('lon', '$x{custom}'),
        ('lat', '$y{custom}'),
    ],
              formatters={
                  '$x': CustomJSHover(code=code % 0),
コード例 #7
0
    def ConfirmedMapPlot(self):
        # Get the tile provider
        tile_provider = get_provider(CARTODBPOSITRON)

        # Create the plot
        plot = figure(x_axis_type="mercator", 
                      y_axis_type="mercator",
                      title=self.title, 
                      tools = 'pan, wheel_zoom, reset',
                      active_drag   = 'pan',
                      active_scroll = 'wheel_zoom')

        # Add the tile streamer to the plot
        plot.add_tile(tile_provider)

        # Set the sizing mode
        plot.sizing_mode = 'stretch_both'

        # Transform from WGS83 to Web Mercator projection
        merc_geo_json_df = self.country_data.to_crs('EPSG:3857')

        # Add the transformed data to a GeoJSONDataSource
        geosource = GeoJSONDataSource(geojson = merc_geo_json_df.to_json())

        # Set the palette and min/max range for the colour mapper
        palette = brewer[self.colour][8]
        palette = palette[::-1]
        min_range = self.country_data[self.column].min()
        max_range = self.country_data[self.column].max()

        # Create the colour mapper
        color_mapper = LogColorMapper(palette = palette, low = min_range, high = max_range)

        # Create a tick formatter
        format_tick = NumeralTickFormatter(format='0.0a')

        # Create a Log Ticker
        log_ticker = LogTicker()

        # Create the colour bar which will go on the right
        color_bar = ColorBar(color_mapper=color_mapper,
                             label_standoff=18,
                             formatter=format_tick,
                             border_line_color=None,
                             location = (0, 0),
                             ticker=log_ticker)

        # Add the data to the circle plot
        plot.patches(xs='xs', 
                     ys='ys', 
                     source=geosource, 
                     line_color=self.line_colour,
                     fill_alpha=0.8, 
                     fill_color={'field' : self.column, 'transform' : color_mapper})

        # Add the colour bar
        plot.add_layout(color_bar, 'right')

        # Add the tooltip
        self.AddToolTip(plot, self.tooltips)

        curdoc().add_root(plot)
コード例 #8
0
 def test_unknown_vendor(self):
     with pytest.raises(ValueError):
         bt.get_provider("This is not a valid tile vendor")
コード例 #9
0
def map_carbon_emission(
    bus_info_and_emission,
    color_coal="black",
    color_ng=be_purple,
    label_coal=u"Coal: CO\u2082",
    label_ng=u"Natural gas: CO\u2082",
    us_states_dat=None,
    size_factor=1,
    web=True,
    agg=True,
    type1="natural gas",
    type2="coal",
):
    """Makes map of carbon emissions, color code by fuel type. Size/area
        indicates emissions.

    :param pandas.DataFrame bus_info_and_emission: info and emission of buses
        as returned by :func:`combine_bus_info_and_emission`.
    :param str color_ng: color assigned for ng, default to BE purple
    :param str color_coal: color associated with coal, default to black/gray
    :param str label_coal: label for legend associated with coal.
    :param str label_ng: label for legend associated with ng.
    :param dict us_states_dat: dictionary of state border lats/lons. If None, get
        from :func:`postreise.plot.plot_states.get_state_borders`.
    :param float size_factor: scaling factor for size of emissions circles glyphs
    :param boolean web: if true, optimizes figure for web-based presentation
    :param boolean agg: if true, aggregates points by lat lon within a given radius
    :param str type1: label for hover over tool tips, first color/type
        (usual choices: natural gas or increase if making a diff map)
    :param str type2: label for hover over tool tips, second color/type
        (usual choices: coal or decrease if making diff map)
    """

    # us states borders, prepare data
    if us_states_dat is None:
        us_states_dat = get_state_borders()
    a, b = project_borders(us_states_dat)

    # prepare data frame for emissions data
    bus_map = _prepare_busmap(bus_info_and_emission,
                              color_ng,
                              color_coal,
                              agg=agg,
                              type1=type1,
                              type2=type2)
    bus_map = bus_map.sort_values(by=["color"])

    bus_source = ColumnDataSource({
        "x":
        bus_map["x"],
        "y":
        bus_map["y"],
        "size": (bus_map["amount"] / 10000 * size_factor)**0.5 + 2,
        "radius": (bus_map["amount"] * 1000 * size_factor)**0.5 + 10,
        "tons":
        bus_map["amount"],
        "color":
        bus_map["color"],
        "type":
        bus_map["type"],
    })

    # Set up figure
    tools: str = "pan,wheel_zoom,reset,save"
    p = figure(
        tools=tools,
        x_axis_location=None,
        y_axis_location=None,
        plot_width=800,
        plot_height=800,
        output_backend="webgl",
        sizing_mode="stretch_both",
        match_aspect=True,
    )
    p_legend = figure(
        x_axis_location=None,
        y_axis_location=None,
        toolbar_location=None,
        plot_width=200,
        plot_height=400,
        y_range=(0, 4),
        x_range=(0, 2),
        output_backend="webgl",
    )

    # circle glyphs that exist only for the web legend,
    # these are plotted behind the tiles, not visible
    p.circle(
        -8.1e6,
        5.2e6,
        fill_color=color_coal,
        color=color_coal,
        alpha=0.5,
        size=50,
        legend_label=label_coal,
    )
    p.circle(
        -8.1e6,
        5.2e6,
        fill_color=color_ng,
        color=color_ng,
        alpha=0.5,
        size=50,
        legend_label=label_ng,
    )

    p.add_tile(get_provider(Vendors.CARTODBPOSITRON_RETINA))
    # state borders
    p.patches(a, b, fill_alpha=0.0, line_color="gray", line_width=2)

    # emissions circles, web version
    if web:

        circle = p.circle(
            "x",
            "y",
            fill_color="color",
            color="color",
            alpha=0.25,
            radius="radius",
            source=bus_source,
        )

    else:
        p.circle(
            "x",
            "y",
            fill_color="color",
            color="color",
            alpha=0.25,
            size="size",
            source=bus_source,
        )

    # legend: white square background and bars per color code
    p_legend.square(1, [1, 3], fill_color="white", color="white", size=300)
    p_legend.square(1, [1, 3],
                    fill_color="white",
                    color="black",
                    size=(2000000 / 100)**0.5)
    p_legend.circle(
        1,
        y=np.repeat([1, 3], 3),
        fill_color=np.repeat([color_coal, color_ng], 3),
        color=np.repeat([color_coal, color_ng], 3),
        alpha=0.25,
        size=[
            (10000000 / 10000 * size_factor)**0.5 + 2,
            (5000000 / 10000 * size_factor)**0.5 + 2,
            (1000000 / 10000 * size_factor)**0.5 + 2,
        ] * 2,
    )
    source = ColumnDataSource(data=dict(
        x=[1, 1, 1, 0.3, 1, 1, 1, 0.3],
        y=[0.9, 1.1, 1.3, 1.55, 2.9, 3.1, 3.3, 3.55],
        text=["1M", "5M", "10M", label_coal, "1M", "5M", "10M", label_ng],
    ))
    labels = LabelSet(
        x="x",
        y="y",
        text="text",
        source=source,
        level="glyph",
        x_offset=0,
        y_offset=0,
        render_mode="css",
    )
    p_legend.add_layout(labels)

    if web:
        p.legend.location = "bottom_right"
        p.legend.label_text_font_size = "12pt"

        hover = HoverTool(
            tooltips=[
                ("Type", "@type"),
                (u"Tons CO\u2082", "@tons"),
            ],
            renderers=[circle],
        )

        p.add_tools(hover)
        return_p = p

    else:
        p.legend.visible = False
        return_p = row(p_legend, p)
    return return_p
コード例 #10
0
ファイル: test_tile_providers.py プロジェクト: zzsnow/bokeh
 def test_attribution(self, name) -> None:
     p = bt.get_provider(getattr(bt, name))
     assert p.attribution == (
         '&copy; <a href="http://downloads.esri.com/ArcGISOnline/docs/tou_summary.pdf">Esri</a>, '
         'Earthstar Geographics'
     )
コード例 #11
0
ファイル: test_tile_providers.py プロジェクト: zzsnow/bokeh
 def test_attribution(self, name) -> None:
     p = bt.get_provider(getattr(bt, name))
     assert p.attribution == (
         '&copy; <a href="https://foundation.wikimedia.org/wiki/Maps_Terms_of_Use">Wikimedia Maps</a> contributors'
     )
コード例 #12
0
ファイル: test_tile_providers.py プロジェクト: zzsnow/bokeh
 def test_attribution(self, name) -> None:
     p = bt.get_provider(getattr(bt, name))
     assert p.attribution == (
         '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
     )
コード例 #13
0
def SIF_Explorer_tab():

    #################################
    # Initialize all layers
    #################################

    # Load from a save file
    if path.exists(LAYERS_FILE):
        with open(LAYERS_FILE, 'rb') as layers_file:
            us_county_layer, us_state_layer, world_grid_2_degree_layer = pickle.load(layers_file)
    # Load from scratch
    else:
        us_county_layer = US_County_Layer()
        us_state_layer = US_State_Layer()
        world_grid_2_degree_layer = US_World_Grid_2_Degree_Layer()
        
        # Save the layers to file
        with open(LAYERS_FILE, 'wb') as layers_file:
            layers = (us_county_layer, \
                        us_state_layer, world_grid_2_degree_layer)
            pickle.dump(layers, layers_file)

    # Want the custom layer to be new every time
    custom_shapes_layer = Custom_Shapes_Layer()
    world_grid_dynamic_layer = World_Grid_Dynamic_Layer()

    # Set the active layer to be the county layer
    active_layer = us_county_layer

    #################################
    # Set up layer selector
    #################################

    # Once a new layer is selected, use that layer to refresh the page
    # and all data
    def refresh_page():
        
        # Get initial map details
        xs, ys, names = active_layer.get_map_details()

        if type(active_layer) != Custom_Shapes_Layer:

            # Obtain and update date boundaries
            start_date, end_date = active_layer.get_date_range()
            date_range_slider.start = start_date
            date_range_slider.end = end_date

            # Unpack the current range
            range_start, range_end = date_range_slider.value

            # Convert to SQL format
            range_start = utc_from_timestamp(range_start)
            range_end = utc_from_timestamp(range_end)

            # Get the initial sif values
            sifs = active_layer.get_data_for_date_range(range_start, 
                                                        range_end)

            # Dictionary to hold the data
            new_source_dict = dict(
                x= xs, y= ys,
                name= np.array(names), sifs= np.array(sifs))
            
            # Update all source data values
            source.data = new_source_dict

            # Turn off custom layer
            custom_data_source.data = dict(x= np.array([]), y= np.array([]), 
                                           name = np.array([]))

        else:

            # Turn off the other layers
            source.data = dict(x= np.array([]), y= np.array([]),
                name= np.array([]), sifs= np.array([]))

            # Safeguard - that at least one custom shape is drawn
            if (xs.size != 0):

                # Dictionary to hold the selected shape data
                new_source_dict = dict(
                    x= xs, y= ys,
                    name = np.array(names))

                custom_data_source.data = new_source_dict


    # Trigger for when a new layer is selected
    def layer_selected(new):

        # We want to modify the overall active layer (not local to this func)
        nonlocal active_layer

        # Simple dictionary to switch out the active layer
        switcher = {
            0 : custom_shapes_layer,
            1 : us_state_layer,
            2 : us_county_layer,
            3 : world_grid_2_degree_layer,
            4 : world_grid_dynamic_layer,
        }

        # Swap out the active layer
        active_layer = switcher.get(new, active_layer) 
            
        # Fetch new dates, shapes, names, etc. and refresh the page
        refresh_page()

    # Define selection labels
    layer_selector = RadioButtonGroup(
        labels=["Custom", "US States", "US Counties", 
                "World", "World (Dynamic)"], active=2)

    # Set up layer selection callback
    layer_selector.on_click(layer_selected)

    #################################
    # Set up date range slider
    #################################

    # Obtain date boundaries
    start_date, end_date = active_layer.get_date_range()

    # create a callback for when the date slider is changed
    def date_range_selected(attr, old, new):

        t0 = time.time()

        # Unpack the new range
        range_start, range_end = new

        # Convert to SQL format
        range_start = utc_from_timestamp(range_start)
        range_end = utc_from_timestamp(range_end)
        
        # Get the new day's data
        sifs = active_layer.get_data_for_date_range(range_start, range_end)

        # Update the sif values
        source.data["sifs"] = np.array(sifs)

        # Set the title of the map to reflect the selected date range
        p.title.text = "SIF Average: %s to %s" % (range_start, range_end)

        print("Took " + str(time.time() - t0) + " seconds to update")

    # Create the date slider
    date_range_slider = DateRangeSlider(title="Date Range: ", 
                                        start=start_date, end=end_date, 
                                        value=(START_DATE_INIT, 
                                            END_DATE_INIT), step=1)

    # Assign the callback for when the date slider changes
    date_range_slider.callback_policy = "throttle"
    date_range_slider.callback_throttle = 200
    date_range_slider.on_change('value_throttled', date_range_selected)

    #################################
    # Set up the map and its source
    #################################

    # Get initial map details
    xs, ys, names = active_layer.get_map_details()

    # Get the initial sif values 
    sifs = active_layer.get_data_for_date_range(START_DATE_INIT, 
                                                END_DATE_INIT)

    # Dictionary to hold the data
    source=ColumnDataSource(data = dict(
        x= np.array(xs),
        y= np.array(ys),
        name= np.array(names),
        sifs= np.array(sifs))
    )

    # Which tools should be available to the user
    TOOLS = "pan,wheel_zoom,reset,hover,save,tap"

    # Obtain map provider
    tile_provider = get_provider(Vendors.CARTODBPOSITRON_RETINA)

    # tile_options = {}
    # tile_options['url'] = 'https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}'
    # tile_options['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>.
    #     """
    # mq_tile_source = WMTSTileSource(**tile_options)

    # Don't want the map to wrap around
    tile_provider.wrap_around = False

    # Configure the figure
    p = figure(
        title="SIF Average by County: %s" % end_date, tools=TOOLS,
        active_scroll = "wheel_zoom",
        x_axis_location=None, y_axis_location=None,
        tooltips=[
            ("Name", "@name"), 
            ("Average SIF", "@sifs")
        ],
        x_axis_type='mercator',
        y_axis_type='mercator',
        plot_height = 900,
        plot_width = 1100,
        output_backend="webgl",
        x_range=Range1d(-20000000, 20000000, bounds = 'auto'))

    # Add the map!
    p.add_tile(tile_provider)

    p.lod_threshold = None          # No downsampling
    #p.lod_interval = 150
    p.toolbar.logo = None           # No logo
    p.grid.grid_line_color = None   # No grid

    # Policy for hovering
    p.hover.point_policy = "follow_mouse"

    # Color mapper
    color_mapper = LinearColorMapper(palette=palette, 
                                     low = SIF_MIN, high = SIF_MAX)
    color_transform = {'field': 'sifs', 'transform': color_mapper}

    # Patch all the information onto the map
    patch_renderer = p.patches('x', 'y', source=source,
                      fill_color=color_transform,
                      fill_alpha=0.9, line_color="white", line_width=0.1, 
                      selection_fill_alpha = 1.0, 
                      selection_fill_color = color_transform,
                      nonselection_line_color="black",
                      nonselection_fill_alpha=0.7,
                      nonselection_fill_color= color_transform)
    p.title.text_font_size = '16pt'

    # Add a color bar
    ticker = FixedTicker(ticks=[-1,0,1,2])
    color_bar = ColorBar(color_mapper=color_mapper, ticker = ticker,
                     label_standoff=12, border_line_color=None, location=(0,0))
    p.add_layout(color_bar, 'right')

    # Add zoom in / out tools
    zoom_in = ZoomInTool(factor=ZOOM_FACTOR)
    zoom_out = ZoomOutTool(factor=ZOOM_FACTOR)

    def range_changed(param, old, new):
        if (type(active_layer) == World_Grid_Dynamic_Layer):
            x1 = p.x_range.start
            x2 = p.x_range.end
            y1 = p.y_range.start
            y2 = p.y_range.end
            new_x1, new_y1 = to_lat_lon(y1, x1)
            new_x2, new_y2 = to_lat_lon(y2, x2)
            if (active_layer.range_changed(new_x1, new_y1, new_x2, new_y2)):
                refresh_page()
            #convert_shapes_to_mercator(np.array([[x1], [x2]]), 
                                                      #np.array([[y1], [y2]]))

            #print("(%s, %s) to (%s, %s)" % (x1, y1, x2, y2))
            #40000000
            #

    # p.callback_policy = "throttle"
    # p.callback_throttle = 200
    p.x_range.on_change('end', range_changed)

    p.add_tools(zoom_in)
    p.add_tools(zoom_out)

    #################################
    # Set up custom plot data
    #################################

    # Data source for custom shapes
    custom_data_source = ColumnDataSource(data = \
                                        dict(x= np.array([]), y= np.array([]), 
                                        name=np.array([])))

    # Patch the custom data onto the map
    p.patches('x', 'y', source=custom_data_source,
                  line_color="darkslategray", line_width=1, 
                  fill_alpha=0.3, fill_color="lightgray")

    # On geometry selection
    # zoom = WheelZoomTool()
    # p.on_event()
    # p.add_tools(lasso)
    # p.on_event(SelectionGeometry, shape_drawn)

    #################################
    # Set up time series
    #################################

    def color_gen():
        yield from itertools.cycle(time_pltt[10])
    color = color_gen()

    def shape_drawn(event):

        # Check if more than one point
        # Otherwise a tap triggers this function
        if (type(event.geometry['x']) != float):

            # Notify the custom selection layer that this
            # shape was selected and obtain relevant info
            # custom_shapes_layer.patch_selected(event)

            # Change to the custom layer
            layer_selector.active = 0
            layer_selected(0)

            # Notify the layer that this patch was created. 
            active_layer.patch_created(event)

            # Clear all time series
            sif_series.renderers = []

            # Update the title and get new data from the active layer
            sif_series.title.text, time_srs_src_list, names = \
                                active_layer.patch_clicked(source, None)

            # Plot each series returned
            for i in range(len(time_srs_src_list)):
                sif_series.scatter('date', 'sif', 
                                    source=time_srs_src_list[i], 
                                    color=time_pltt[10][i])
            # Make sure the current shape is drawn
            refresh_page()

    def patch_clicked(event):
        """ When a patch is clicked, update the time series chart. """

        # Clear all time series
        sif_series.renderers = []

        # Update the title and get new data from the active layer
        sif_series.title.text, time_srs_src_list, names = \
                            active_layer.patch_clicked(source, event)

        # Plot each series returned
        for i in range(len(time_srs_src_list)):
            sif_series.scatter('date', 'sif', 
                                source=time_srs_src_list[i], 
                                color=time_pltt[10][i])

    # Which tools should be available to the user for the timer series
    TOOLS = "pan,wheel_zoom,reset,hover,save"

    # Figure that holds the time-series
    sif_series = figure(plot_width=750, plot_height=400, x_axis_type='datetime',
                        tools=TOOLS, 
                        title= "SIF Time-Series (Select a county...)",
                        active_scroll = "wheel_zoom",
                        tooltips=[
                            ("Day", "@date"), 
                            ("Average SIF", "@sif")
                        ],
                        x_axis_label = 'Date',
                        y_axis_label = 'SIF Average',
                        y_range = (SIF_MIN, SIF_MAX))

    # Some font choices
    sif_series.title.text_font_size = '16pt'
    sif_series.xaxis.axis_label_text_font_size = "12pt"
    sif_series.yaxis.axis_label_text_font_size = "12pt"

    # Policy for hovering
    sif_series.hover.point_policy = "follow_mouse"

    # No logo
    sif_series.toolbar.logo = None

    # When a patch is selected, trigger the patch_time_series function
    p.on_event(Tap, patch_clicked)
    
    # On geometry selection
    lasso = LassoSelectTool(select_every_mousemove = False)
    p.add_tools(lasso)
    p.on_event(SelectionGeometry, shape_drawn)

    #################################
    # TODO: Set up download area
    #################################
    # def save_data():
    #     active_layer.save_data()
    #     print("Button Clicked")

    # callback = active_layer.get_save_data_js_callback()

    button = Button(label="Save Data", button_type="success")
    # button.on_click(active_layer.save_data)
    #button.js_on_event(ButtonClick, callback)

    #################################
    # Set up tab
    #################################

    # The layout of the view
    layout = row(column(p, date_range_slider, layer_selector), 
                 column(sif_series, row(column(), button)))

    # Create tab using layout
    tab = Panel(child=layout, title = 'US Visualization')

    # Return the created tab
    return tab
コード例 #14
0
data_2017_map['dot_size'].values[data_2017_map['dot_size']<0]=0.01
data_2017_map['dot_size'].values[data_2017_map['dot_size']>80]=80
#data_2017_map.sort_values(by='dot_size', ascending=False)
output_file('map_of_personal_income.html')
cds = ColumnDataSource(data_2017_map)

hover = HoverTool(tooltips=[('City', '@City'),
                            ('Zip Code', '@Zip_Code'),
                           ('Avg AGI', '@Avg_AGI'),
                           ('Avg Tax Liability', '@Avg_Tax_Liability')],
                  mode='mouse')
up = figure(title='Avg Personal Income in CA',
           plot_width=1000, plot_height=1000,
           x_axis_location=None, y_axis_location=None, 
           tools=['pan', 'wheel_zoom', 'tap', 'reset', 'crosshair', hover])
tile_provider=get_provider(Vendors.CARTODBPOSITRON_RETINA)
up.add_tile(tile_provider)
mypalette=Category20b[20]+Category20c[20]+Spectral[4]+Plasma[256]+Viridis[256]+Inferno[256]+Magma[256]

mapper = CategoricalColorMapper(factors=data_2017_map.County, 
                                palette=mypalette)

scatter = up.circle('x', 'y', source=cds, size='dot_size',
                    color={'field': 'City','transform': mapper}, alpha=.4,
                    selection_color='black',
                    nonselection_fill_alpha=.1,
                    nonselection_fill_color='gray',)
down = figure(title='Personal Income (Click bar below)',
              x_range=data_2017_map.County.unique(),
              plot_width=1000, plot_height=500,
              tools=['tap', 'reset'])
コード例 #15
0
def create_us_map_tab():
    "Factory for creating second tab of app: US Only Data"

    ## Data Sources
    source_df_confirmed, source_CDS = get_time_series_confirmed_US_data()
    source_CDS.data['number_per_capita'] = source_df_confirmed[
        START_DATE_STRING] / source_df_confirmed['population']

    ## Map
    color_mapper = log_cmap(field_name='number',
                            palette=Spectral6,
                            low=1,
                            high=1e6)

    TOOLTIPS = [('County/Region', '@county'), ('State/Province', '@region'),
                ('Population', '@population'), ('Cases', '@number'),
                ('Cases Per Capita', '@number_per_capita')]

    map_figure = figure(
        title='Confirmed COVID-19 Cases in the United States',
        tooltips=TOOLTIPS,
        x_range=(-18367715, -6901808.43),
        y_range=(0, 13377019.78),
        x_axis_type='mercator',
        y_axis_type='mercator',
        active_scroll='wheel_zoom',
    )

    tile_provider = get_provider(CARTODBPOSITRON)
    map_figure.add_tile(tile_provider)
    map_figure.circle(x='web_mercator_x',
                      y='web_mercator_y',
                      source=source_CDS,
                      size='sizes',
                      color=color_mapper)

    ## Colorbar
    color_bar = ColorBar(title='Num. Cases',
                         title_standoff=20,
                         color_mapper=color_mapper['transform'],
                         label_standoff=20,
                         width=8,
                         location=(0, 0),
                         ticker=LogTicker())
    color_bar.formatter.use_scientific = False
    map_figure.add_layout(color_bar, 'right')

    ## Slider
    def slider_callback(attr, old, new):
        delta = datetime.timedelta(milliseconds=new)
        date = datetime.date(1970, 1, 1) + delta
        date_string = date.strftime('%Y-%m-%d')

        try:
            source_CDS.data['number'] = source_df_confirmed[date_string]
            source_CDS.data['sizes'] = source_df_confirmed[date_string].apply(
                scale)
            source_CDS.data['number_per_capita'] = source_df_confirmed[
                date_string] / source_df_confirmed['population']
        except KeyError:
            pass

    slider = DateSlider(title='Date',
                        start=START_DATE,
                        end=datetime.date.today(),
                        step=1,
                        value=START_DATE)
    slider.on_change('value', slider_callback)

    ## Data Table
    columns = [
        TableColumn(field='county', title='County/Region'),
        TableColumn(field='region', title='State/Province'),
        TableColumn(field='population', title='Population'),
        TableColumn(field='number', title='Cases'),
        TableColumn(field='number_per_capita', title='Cases Per Capita'),
    ]

    data_table = DataTable(
        source=source_CDS,
        columns=columns,
    )

    ## Cancel Selection Button
    def cancel_selection_callback():
        source_CDS.selected.indices = []

    cancel_selection_button = Button(label='Clear Selection',
                                     button_type='warning')
    cancel_selection_button.on_click(cancel_selection_callback)

    child = row([
        column([slider, map_figure]),
        column([data_table, cancel_selection_button])
    ])

    return Panel(child=child, title='United States Map')
コード例 #16
0
 def test_attribution(self, name) -> None:
     p = bt.get_provider(getattr(bt, name))
     assert p.attribution == xyz.OpenStreetMap.Mapnik.html_attribution
コード例 #17
0
ファイル: tile_source.py プロジェクト: digitalsatori/Bokeh
from bokeh.plotting import figure, show, output_file
from bokeh.tile_providers import get_provider, Vendors

output_file("tile_source.html")

# create plot and add tools
p = figure(x_range=(-2000000, 2000000), y_range=(1000000, 7000000),
           x_axis_type="mercator", y_axis_type="mercator")
p.add_tile(get_provider(Vendors.CARTODBPOSITRON))

show(p)
コード例 #18
0
def map_carbon_emission_bar(
    bus_info_and_emission,
    scenario_name,
    color_coal="black",
    color_ng="purple",
    us_states_dat=None,
    size_factor=1.0,
):
    """Makes map of carbon emissions, color code by fuel type. Size/area
    indicates emissions.

    :param dict us_states_dat: dictionary of state border lats/lons. If None, get
        from :func:`postreise.plot.plot_states.get_state_borders`.
    :param pandas.DataFrame bus_info_and_emission: info and
        emission of buses by :func:`combine_bus_info_and_emission`.
    :param str scenario_name: name of scenario for labeling.
    :param str color_coal: color assigned for coal
    :param str color_ng: color assigned for natural gas
    :param float size_factor: height scale for bars
    """

    if us_states_dat is None:
        us_states_dat = get_state_borders()

    bus_map = project_bus(bus_info_and_emission)
    bus_map = group_zone(bus_map)

    a, b = project_borders(us_states_dat)

    # plotting adjustment constants
    ha = 85000
    size_factor = size_factor * 0.02

    bus_source = ColumnDataSource({
        "x":
        bus_map["x"],
        "x2":
        bus_map["x"] + ha * 2,
        "y":
        bus_map["y"],
        "coaly":
        bus_map["y"] + bus_map["coal"] * size_factor,
        "ngy":
        bus_map["y"] + bus_map["ng"] * size_factor,
    })

    # Set up figure
    tools: str = "pan,wheel_zoom,reset,hover,save"
    p = figure(
        title=scenario_name,
        tools=tools,
        x_axis_location=None,
        y_axis_location=None,
        plot_width=800,
        plot_height=800,
    )
    p_legend = figure(
        x_axis_location=None,
        y_axis_location=None,
        toolbar_location=None,
        plot_width=200,
        plot_height=200,
        y_range=(0, 2),
        x_range=(0, 2),
    )
    p.add_tile(get_provider(Vendors.CARTODBPOSITRON_RETINA))
    # state borders
    p.patches(a, b, fill_alpha=0.0, line_color="black", line_width=2)

    # emissions bars
    width = 150000.0
    alpha = 0.7
    p.vbar(
        x="x2",
        bottom="y",
        top="coaly",
        width=width,
        color=color_coal,
        source=bus_source,
        alpha=alpha,
    )
    p.vbar(
        x="x",
        bottom="y",
        top="ngy",
        width=width,
        color=color_ng,
        source=bus_source,
        alpha=alpha,
    )
    bus_map = pd.DataFrame(bus_map)

    # citation fields
    cit_x = []
    cit_y = []
    cit_text = []

    # constants for adjustments of text labels
    va = 1000
    m = 1000000

    # x values are offset so vbars are side by side.
    cit_x.append([i - ha * 1.5 for i in bus_map.x.values.tolist()])
    cit_x.append([i + ha for i in bus_map.x.values.tolist()])
    cit_y.append(
        np.add(
            [i + va * 2 for i in bus_map.y.values.tolist()],
            [i * size_factor for i in bus_map.ng.values.tolist()],
        ))
    cit_y.append(
        np.add(
            [i + va * 2 for i in bus_map.y.values.tolist()],
            [i * size_factor for i in bus_map.coal.values.tolist()],
        ))
    cit_text.append(
        [round(num, 1) for num in [i / m for i in bus_map.ng.values.tolist()]])
    cit_text.append([
        round(num, 1) for num in [i / m for i in bus_map.coal.values.tolist()]
    ])

    for j in range(0, len(cit_x)):
        for i in range(0, len(cit_x[j])):
            citation = Label(
                x=cit_x[j][i],
                y=cit_y[j][i],
                x_units="data",
                y_units="data",
                text_font_size="20pt",
                text=str(cit_text[j][i]),
                render_mode="css",
                border_line_color="black",
                border_line_alpha=0,
                background_fill_color="white",
                background_fill_alpha=0.8,
            )
            p.add_layout(citation)

    # custom legend
    p_legend.square(1, 1, fill_color="white", color="white", size=600)
    p_legend.square(1, 1, fill_color="white", color="black", size=400)
    p_legend.square(0.4,
                    0.8,
                    fill_color="black",
                    color="black",
                    size=40,
                    alpha=0.7)
    p_legend.square(0.4,
                    0.2,
                    fill_color="purple",
                    color="purple",
                    size=40,
                    alpha=0.7)
    source = ColumnDataSource(data=dict(
        x=[0.7, 0.7, 0.05],
        y=[0.6, 0.1, 1.5],
        text=["Coal", "Natural Gas", "Emissions (Million Tons)"],
    ))
    labels = LabelSet(
        x="x",
        y="y",
        text="text",
        source=source,
        level="glyph",
        x_offset=0,
        y_offset=0,
        render_mode="css",
        text_font_size="20pt",
    )
    p_legend.add_layout(labels)

    return row(p_legend, p)
コード例 #19
0
def show_data_visualization(source):
    """Show the data visualization in a webpage."""
    # Set up the plot window
    # Another map tile option: Vendors.STAMEN_TERRAIN)
    tile_provider = get_provider(Vendors.CARTODBPOSITRON)
    sf_lat = (37.73, 37.81)
    sf_long = (-122.47, -122.359720)
    sf_xrange = [long_to_merc(long) for long in sf_long]
    sf_yrange = [lat_to_merc(lat) for lat in sf_lat]
    plot_options = dict(plot_width=1000, plot_height=800, title='Hourly Net Change in Bikes Docked')
    p = figure(x_range=sf_xrange, y_range=sf_yrange,
               x_axis_type="mercator", y_axis_type="mercator",
               tooltips=[("Net Change", "@net_change"), ("ID", "@id"), ("Station", "@name")],
               **plot_options)
    p.add_tile(tile_provider)
    # Add a color bar
    palette = RdBu[11]
    palette.reverse()
    color_mapper = LinearColorMapper(palette=palette, low=-30, high=30)
    color_bar = ColorBar(color_mapper=color_mapper, ticker=AdaptiveTicker(),
                         label_standoff=12, border_line_color=None, location=(0,0))
    p.add_layout(color_bar, 'right')
    # Add the station points as circles
    p.circle(x='x', y='y', size=15,
             fill_color={'field': 'net_change', 'transform': color_mapper},
             fill_alpha=0.8, source=source,
             )
    # add two sliders: one for date, one for hour
    start_date, end_date = datetime.date(2019,9,1), datetime.date(2019,9,30)
    date_fmt = '%Y%m%d'
    # Out of simplicity, setting the dates to ints to make the slider work here
    date_slider = Slider(start=int(start_date.strftime(date_fmt)), end=int(end_date.strftime(date_fmt)), step=1, value=int(start_date.strftime(date_fmt)), title='Date')
    hour_slider = Slider(start=0, end=23, value=9, step=1, title="Hour of Day")
    date_callback = CustomJS(args=dict(source=source), code="""
        var data = source.data;
        var curr_date = cb_obj.value;
        data['net_change'] = data[curr_date + ' ' + data['curr_hr'][0]];
        source.change.emit();
    """)
    hour_callback = CustomJS(args=dict(source=source), code="""
        var data = source.data;
        function pad(n, width, z) {
          z = z || '0';
          n = n + '';
          return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
        }
        var curr_hr = String(cb_obj.value).padStart(2, '0');
        data['curr_hr'][0] = curr_hr;
        data['net_change'] = data[data['curr_date'][0] + ' ' + curr_hr];
        source.change.emit();
    """)
    output_file("net_bikes.html")
    date_slider.js_on_change('value', date_callback)
    hour_slider.js_on_change('value', hour_callback)
    # Display on the page
    show(
        column(
            row(
                widgetbox(date_slider),
                widgetbox(hour_slider),
            ),
            p
        )
    )
コード例 #20
0
ファイル: cluster_gui.py プロジェクト: braunfuss/Palantiri
def cluster_gui(doc):
    global s2, s1, old_indices
    old_indices = []
    output_file("tile.html")
    tile_provider = get_provider(CARTODBPOSITRON)
    x = []
    y = []
    name = []
    global fig03
    fig03 = figure(
        plot_width=400,
        plot_height=400,
        tools=["box_zoom", "wheel_zoom", "reset", "save"],
        title="Waveforms from current selection",
    )
    for i, st in enumerate(stations):
        xm, ym = merc(st.lat, st.lon)
        x.append(xm)
        y.append(ym)
        name.append(st.nsl_string())

    # create first subplot
    plot_width = 400
    plot_height = 400
    d = num.ones_like(x)

    s1 = ColumnDataSource(data=dict(x=x, y=y, ind=d, name=name))
    # range bounds supplied in web mercator coordinates
    fig01 = figure(
        x_axis_type="mercator",
        y_axis_type="mercator",
        plot_width=plot_width,
        plot_height=plot_height,
        tools=[
            "lasso_select", "box_select", "reset", "save", "box_zoom",
            "wheel_zoom"
        ],
        title="Select",
    )
    fig01.add_tile(tile_provider)

    fig01.scatter("x", "y", source=s1, alpha=0.6, size=8)

    # create second subplot
    s2 = ColumnDataSource(data=dict(x=[], y=[], ind=[], name=[]))

    color_mapper = LinearColorMapper(palette='Magma256', low=1, high=100)

    fig02 = figure(
        x_axis_type="mercator",
        y_axis_type="mercator",
        plot_width=plot_width,
        plot_height=plot_height,
        x_range=(num.min(x), num.max(x)),
        y_range=(num.min(y), num.max(y)),
        tools=["box_zoom", "wheel_zoom", "reset", "save"],
        title="Stations selected for Array",
    )
    fig02.add_tile(tile_provider)

    fig02.scatter("x",
                  "y",
                  source=s2,
                  alpha=1,
                  color={
                      'field': 'ind',
                      'transform': color_mapper
                  },
                  size=8)

    x_event, y_event = merc(event.lat, event.lon)
    fig01.scatter(x_event, y_event, size=8, color="red")
    fig02.scatter(x_event, y_event, size=8, color="red")

    columns = [
        TableColumn(field="x", title="X axis"),
        TableColumn(field="y", title="Y axis"),
        TableColumn(field="ind", title="indices"),
        TableColumn(field="name", title="name"),
    ]

    table = DataTable(
        source=s2,
        columns=columns,
        width=400,
        height=600,
        sortable=True,
        selectable=True,
        editable=True,
    )

    source_count = 0
    callback_slider = CustomJS(code="""
        source_count = slider.value;
        """)
    global slider

    slider = Slider(start=1, end=100, value=1, step=1, title="Array number")
    slider.js_on_change('value', callback_slider)

    s1.selected.js_on_change(
        "indices",
        CustomJS(args=dict(s1=s1, s2=s2, s3=slider, table=table),
                 code="""
            var inds = cb_obj.indices;
            var d1 = s1.data;
            var d2 = s2.data;
            const A = s3.value;

            for (var i = 0; i < inds.length; i++) {
                d2['x'].push(d1['x'][inds[i]])
                d2['y'].push(d1['y'][inds[i]])
                d2['name'].push(d1['name'][inds[i]])
                d2['ind'].push(A)
            }
            s2.change.emit();
            table.change.emit();
    	    s2.data = s2.data;

            var inds = source_data.selected.indices;
            var data = source_data.data;
            var out = "name, x, y, ind\\n";
            for (i = 0; i < inds.length; i++) {
                out += data['name'][inds[i]] + "," + data['x'][inds[i]] + "," + data['y'][inds[i]] + "," + data['ind'][inds[i]]   + "\\n";
            }
            var file = new Blob([out], {type: 'text/plain'});

        """),
    ),

    savebutton = Button(label="Save", button_type="success")
    savebutton.callback = CustomJS(
        args=dict(source_data=s1),
        code="""
            var inds = source_data.selected.indices;
            var data = source_data.data;
            var out = "name, x, y, ind\\n";
            for (i = 0; i < inds.length; i++) {
                out += data['name'][inds[i]] + "," + data['x'][inds[i]] + "," + data['y'][inds[i]] + "," + data['ind'][inds[i]]   + "\\n";
            }
            var file = new Blob([out], {type: 'text/plain'});
            var elem = window.document.createElement('a');
            elem.href = window.URL.createObjectURL(file);
            elem.download = 'arrays.txt';
            document.body.appendChild(elem);
            elem.click();
            document.body.removeChild(elem);
            """,
    )

    tooltips = [
        ("X:", "@x"),
        ("Y:", "@y"),
        ("Array:", "@ind"),
        ("Station:", "@name"),
    ]

    fig01.add_tools(HoverTool(tooltips=tooltips))
    fig02.add_tools(HoverTool(tooltips=tooltips))
    fig03.add_tools(HoverTool(tooltips=tooltips))

    endbutton = Button(label="End and proceed", button_type="success")
    endbutton.on_click(button_callback)

    clearbutton = Button(label="Clear all", button_type="success")
    clearbutton.on_click(clearbuttonlast_callback)
    clearbuttonlast = Button(label="Clear last selection",
                             button_type="success")
    clearbuttonlast.on_click(clearbuttonlast_callback)
    clearbuttonone = Button(label="Remove one from list",
                            button_type="success")
    clearbuttonone.on_click(clearbuttonone_callback)

    b = Button(label="Reset all plots")
    b.js_on_click(
        CustomJS(code="""\
document.querySelectorAll('.bk-tool-icon-reset[title="Reset"]').forEach(d => d.click())
"""))
    #layout = grid([fig01, fig02, table, fig03, slider, clearbuttonlast, clearbutton, savebutton, endbutton], ncols=3, nrows=4)
    global text_input
    text_input = TextInput(value="1", title="Array number:")

    buttons = column(clearbuttonlast, clearbuttonone, clearbutton, savebutton,
                     endbutton)
    inputs = column(text_input, slider)

    layout_grid = layout([fig01, fig02, buttons], [fig03, inputs, table])

    #curdoc().add_root(layout)
    cluster_result = []
    doc.add_root(layout_grid)
    #global session
    #session = push_session(curdoc())

    #curdoc().add_periodic_callback(update, 100)
    #session.show(layout)
    doc.add_periodic_callback(update, 900)
    curdoc().title = "Array selection"
コード例 #21
0
ファイル: plot.py プロジェクト: ronyarmon/geohealth
def map_plot(data, features_titles, output_choice_selection):
    full_source = ColumnDataSource(data)  # a CDS version of the data obtained

    # a CDS version of the data to plot, modifiable by geo dropdowns, to be produced in the callback
    num_instances = len(data)

    # Split the columns with the values to plot to build their marks and title
    geo_columns = [
        'practice_code', 'practice', 'ccg', 'region', 'sub_region',
        'longitudemerc', 'latitudemerc'
    ]
    value_columns = [h for h in data.columns if h not in geo_columns]

    # Assert gender-age as the second value (to be marked by size)
    if value_columns[0] in ['gender', 'age_groups', 'gender_age_groups']:
        value_columns = list(reversed(value_columns))

    first_value = value_columns[0]
    features_marks = {first_value: 'Color'}
    hover_first_value = '@{fv}'.format(fv=first_value)

    # Normalized size values for the second feature if such exists
    if len(value_columns) == 2:
        second_value = value_columns[1]
        sv_column = np.array(data[second_value])
        svinterp = np.interp(sv_column, (sv_column.min(), sv_column.max()),
                             (0, 2000))  #was 10 for size
        if second_value == 'deprivation':
            svinterp = max(svinterp) - svinterp
        norm_header = second_value + '_norm'
        data[norm_header] = svinterp
        features_marks[second_value] = 'Size'

    source = ColumnDataSource(data)
    filter = IndexFilter(indices=list(data.index))
    view = CDSView(source=source, filters=[filter])
    plot = figure(x_axis_type="mercator",
                  y_axis_type="mercator",
                  plot_height=700,
                  plot_width=700)
    plot.title.text_color = 'purple'
    tooltips = [('Practice', '@practice'), ('CCG', '@ccg'),
                (first_value.capitalize(), hover_first_value)]

    # Title
    title_parts = []
    for feature, title in features_titles.items():
        title_part = '  {m}: {t}'.format(m=features_marks[feature], t=title)
        title_parts.append(title_part)

    title_parts = list(reversed(title_parts))
    for title_part in title_parts:
        plot.add_layout(
            Title(text=title_part, text_font_size="10pt", text_color='purple'),
            'above')

    # Color mapper
    palette = list(reversed(brewer['YlOrRd'][9]))
    if first_value == 'deprivation':
        low_boundary, high_boundary = max(source.data[first_value]), min(
            source.data[first_value])
    else:
        high_boundary, low_boundary = max(source.data[first_value]), min(
            source.data[first_value])

    mapper = linear_cmap(field_name=first_value, palette=palette,\
    low=low_boundary, high=high_boundary) #Spectral6

    # add map tiles
    map_tile = get_provider(Vendors.CARTODBPOSITRON)
    plot.add_tile(map_tile)

    if len(value_columns) == 2:
        hover_second_value = '@{sv}'.format(sv=second_value)
        tooltips.append((second_value.capitalize(), hover_second_value))

        plot.circle(source=source, x='latitudemerc',y='longitudemerc',\
        hover_color='red', color=mapper,radius = norm_header, alpha=0.2,\
        view = view)
    else:
        plot.circle(source=source, view=view, x='latitudemerc',y='longitudemerc',\
        hover_color='red', color=mapper)

    hover = HoverTool(tooltips=tooltips)
    color_bar = ColorBar(color_mapper=mapper['transform'],
                         width=8,
                         location=(0, 0))
    plot.add_layout(color_bar, 'right')
    plot.add_tools(hover)

    # Plot widgets selection callback
    callback = CustomJS(args=dict(source=source, filter=filter),
                        code='''
      var indices = []
      var selected_value = cb_obj.value
      if (selected_value=='All') {
        indices = source.index
        console.log ('all ccgs selected')
      } else {
      console.log('The selected area is ' + selected_value)
      for (var i = 0; i < source.get_length(); i++) {
        // console.log(i, source.data['ccg'][i], cb_obj.value)
        if ((source.data['ccg'][i] == selected_value) || (source.data['region'][i] == selected_value)\
        ||  (source.data['sub_region'][i] == selected_value)) {
          indices.push(i)
             }
            }
          }
      filter.indices = indices
      source.change.emit()
    ''')

    select_ccg = Select(title='CCG', value=ccgs[0], options=ccgs, width=120)
    select_ccg.js_on_change('value', callback)
    select_region = Select(title='Region',
                           value=regions[0],
                           options=regions,
                           width=120)
    select_region.js_on_change('value', callback)
    select_sub_region = Select(title='Sub-Region',
                               value=sub_regions[0],
                               options=sub_regions,
                               width=120)
    select_sub_region.js_on_change('value', callback)
    view = CDSView(source=source, filters=[filter])

    if output_choice_selection == 'Notebook':
        output_notebook()
    elif output_choice_selection == 'HTML File':
        output_file('plot.html')
    show(row(column(select_region, select_sub_region, select_ccg), plot))
コード例 #22
0
 def test_unknown_vendor(self):
     with pytest.raises(ValueError):
         bt.get_provider("This is not a valid tile vendor")
コード例 #23
0
def update_map(map_geodf):

    # filter map_geodf
    map_geodf_img = map_geodf.copy().dropna(subset=["img_sd"])
    map_geodf_noimg = map_geodf.copy()[map_geodf["img_sd"].isna()]

    # create a geodatasource
    geosource_img = GeoJSONDataSource(geojson=map_geodf_img.to_json())
    geosource_noimg = GeoJSONDataSource(geojson=map_geodf_noimg.to_json())

    # Description from points
    TOOLTIPS1 = """
            <div style="margin: 5px; width: 300px" >
            <img
                src="@img_sd" alt="@img_sd" height=200
                style="margin: 0px;"
                border="2"
                ></img>
                <h3 style='font-size: 10px; font-weight: bold;'>@id</h3>
                <p style='font-size: 10px; font-weight: light; font-style: italic;'>@creator</p>
            
            </div>
        """
    TOOLTIPS2 = """
            <div style="margin: 5px; width: 300px" >
                <h3 style='font-size: 10px; font-weight: bold;'>@id</h3>
                <p style='font-size: 10px; font-weight: light; font-style: italic;'>@creator</p>
            </div>
        """
    callback_tp = CustomJS(code="""
                                var tooltips = document.getElementsByClassName("bk-tooltip");
                                for (var i = 0, len = tooltips.length; i < len; i ++) {
                                    tooltips[i].style.top = ""; 
                                    tooltips[i].style.right = "";
                                    tooltips[i].style.bottom = "0px";
                                    tooltips[i].style.left = "0px";
                                }
                                """)

    # Base map
    maps = figure(
        x_axis_type="mercator",
        y_axis_type="mercator",
        plot_width=1400,
        plot_height=900,
        toolbar_location=None,
    )

    tile_provider = get_provider(Vendors.CARTODBPOSITRON_RETINA)
    maps.add_tile(tile_provider)

    # construct points and wedges from hover
    viewcone1 = maps.patches(
        xs="xs",
        ys="ys",
        source=geosource_img,
        fill_color="white",
        fill_alpha=0,
        line_color=None,
        hover_alpha=0.7,
        hover_fill_color="grey",
        hover_line_color="grey",
    )

    viewcone2 = maps.patches(
        xs="xs",
        ys="ys",
        source=geosource_noimg,
        fill_color="white",
        fill_alpha=0,
        line_color=None,
        hover_alpha=0.7,
        hover_fill_color="grey",
        hover_line_color="grey",
    )

    point_noimg = maps.circle(
        x="lat2",
        y="lng2",
        source=geosource_noimg,
        size=7,
        fill_color="orange",
        fill_alpha=0.5,
        line_color="dimgray",
    )

    point_img = maps.circle(
        x="lat2",
        y="lng2",
        source=geosource_img,
        size=7,
        fill_color="orange",
        fill_alpha=0.5,
        line_color="dimgray",
    )

    # create a hovertool
    h1 = HoverTool(
        renderers=[point_img],
        tooltips=TOOLTIPS1,
        mode="mouse",
        show_arrow=False,
        callback=callback_tp,
    )
    h2 = HoverTool(
        renderers=[point_noimg],
        tooltips=TOOLTIPS2,
        mode="mouse",
        show_arrow=False,
        callback=callback_tp,
    )

    maps.add_tools(h1, h2)
    maps.toolbar.active_scroll = maps.select_one(WheelZoomTool)
    maps.xaxis.major_tick_line_color = None
    maps.xaxis.minor_tick_line_color = None
    maps.yaxis.major_tick_line_color = None
    maps.yaxis.minor_tick_line_color = None
    maps.xaxis.major_label_text_font_size = "0pt"
    maps.yaxis.major_label_text_font_size = "0pt"

    return maps
コード例 #24
0
        import pandas as pd
        import numpy as np
        from sklearn.cluster import KMeans
        from scipy.spatial.distance import cdist

        from sklearn.cluster import SpectralClustering
        import networkx as nx
        from sklearn.preprocessing import MinMaxScaler
        from sklearn.cluster import OPTICS
        #import des modules bokeh
        from bokeh.plotting import figure
        from bokeh.models import HoverTool, ColumnDataSource
        from bokeh.tile_providers import get_provider

        tuile = get_provider('CARTODBPOSITRON_RETINA')
        import warnings
        warnings.filterwarnings("ignore")

        # Lecture du dataframe nettoyé
        df_ville = pd.read_csv('df_paris_bokeh.csv', sep=';')

        #Conversion des données epsg:4326 en espg:3857
        ##Conversion déjà faite dans le csv de départ. Pour un nv fichier, appliquer
        ##le code ci-dessous
        #k=6378137
        #df_ville['X'] = df_ville['X'].apply(lambda x: x*(k * np.pi / 180.0))
        #df_ville['Y'] = df_ville['Y'].apply(lambda x: np.log(np.tan((90 + x) * np.pi / 360.0)) * k)

        #######################################################################
        # Sélection des paramètres utilisateur
コード例 #25
0
ファイル: visualise.py プロジェクト: LKprog/bonsai
    def visualise(self, map, trajects, score_csv):
        """
        method that creates a visual representation of the given trajects
        """

        # load Station data and store the x-coordinates, y-coordinates and the station names in seperate lists.
        merc_y = []
        merc_x = []
        stations = []

        for station in map.stations:
            stations.append(map.stations[station].name)
            new_coord = self.create_coordinates(float(map.stations[station].x), float(map.stations[station].y))
            merc_y.append(float(new_coord[1]))
            merc_x.append(float(new_coord[0]))

        # convert x- and y-lists to numpy array so they can be used in bokeh
        longitude = np.array(merc_y)
        latitude = np.array(merc_x)
        N = 4000

        # save data in a variable for later use
        source = ColumnDataSource(data=dict(latitude=latitude, longitude=longitude, stations=stations))

        # output to html-file
        output_file("color_scatter.html", title="color_scatter.py example", mode="cdn")

        # retrieves a map which serves as a background for the plot
        tile_provider = get_provider(CARTODBPOSITRON)

        # create a new plot with the specified tools, and explicit ranges
        TOOLS = "pan,wheel_zoom,box_zoom,reset,box_select,lasso_select"
        p = figure(x_range=(400000, 500000), y_range=(6700000, 7000000),
            x_axis_type="mercator", y_axis_type="mercator")
        font = 1

        # adds the background to the plot
        p.add_tile(tile_provider)

        # define colors for the different routes
        colors = ['red', 'yellow', 'green', 'black', 'blue', 'orange', 'purple', 'pink', 'lawngreen', 'teal', 'saddlebrown', 'gold', 'magenta', 'silver']

        # creates a line, representing a traject for each of the given trajects
        for values in trajects.values():
            x_list = []
            y_list = []

            for value in values:

                if value in map.stations:
                    new_coord = self.create_coordinates(float(map.stations[value].x), float(map.stations[value].y))
                    x_list.append(float(new_coord[1]))
                    y_list.append(float(new_coord[0]))

            color = colors.pop(0)
            colors.append(color)
            p.line(y_list, x_list, line_width=2, color=color, legend_label=f"{values[0]} || {values[-1]}")

        # legend settings
        p.legend.location = 'top_left'
        p.legend.click_policy="hide"

        # add a circle for each of the stations in the given map
        p.circle(latitude, longitude)

        # adds name-labels to the circles
        labels = LabelSet(x='latitude', y='longitude', text='stations', text_font_size='5pt', level='glyph',
                    x_offset=5, y_offset=5, source=source, render_mode='canvas')

        p.add_layout(labels)

        # show the results
        show(p)

        # make histogram of the "..-scores.csv"
        self.histogram(score_csv)
コード例 #26
0
ファイル: main.py プロジェクト: DillyPickly/buffalo_sales
           'modified_buffalo_assessment_2020-2021.csv')
df = load_data(uri)

# Initial Data
x_range = (df['x'].min(), df['x'].max())
y_range = (df['y'].min(), df['y'].max())
date_range = (df['DEED YEAR'].min(), df['DEED YEAR'].max())
initial_date = (2013, 2019)
df_temp = df[(df['DEED YEAR'] >= initial_date[0])
             & (df['DEED YEAR'] <= initial_date[1])]
df_temp = df_temp[(df_temp['PROPERTY CLASS'] >= 200)
                  & (df_temp['PROPERTY CLASS'] < 300)]
source = ColumnDataSource(df_temp)

# Initialize Figure
tile_provider = get_provider(CARTODBPOSITRON_RETINA)
# tile_provider = get_provider(ESRI_IMAGERY)

p = figure(
    x_range=x_range,
    y_range=y_range,
    x_axis_type="mercator",
    y_axis_type="mercator",
    aspect_ratio=.9,
    sizing_mode='scale_both',
    align='center',
    output_backend="webgl",
)
p.add_tile(tile_provider)
p.add_tools(
    HoverTool(tooltips=[
コード例 #27
0
import datetime as dt
from math import sqrt

import numpy as np
import pandas as pd
from bokeh import palettes, tile_providers
from bokeh.layouts import column, row
from bokeh.models import PanTool, ZoomInTool, ZoomOutTool, ResetTool, HoverTool, Range1d, LinearAxis, Title
from bokeh.plotting import figure

from .utils import tooltip, make_tools
from ..frame import present
from ...stoats.names import DISTANCE_KM, LOCAL_TIME, TIMESPAN_ID, TIME, CLIMB_DISTANCE, ELEVATION_M, CLIMB_ELEVATION, \
    SPHERICAL_MERCATOR_X, SPHERICAL_MERCATOR_Y, LATITUDE, LONGITUDE, ACTIVE_DISTANCE, ACTIVE_TIME, TOTAL_CLIMB

STAMEN_TERRAIN = tile_providers.get_provider(
    tile_providers.Vendors.STAMEN_TERRAIN)

# todo - make selection of hover tool with name='with_hover' universal


def subtract(a, c, key, col):
    cols = [key, col]
    limit = min(a[key].max(), c[key].max())
    a = a.loc[a[key] <= limit, cols]
    c = c.loc[c[key] <= limit, cols]
    both = a.merge(c, how='outer', on=key, sort=True, suffixes=('_a', '_c'))
    both.interpolate(inplace=True, limit_direction='both')
    return pd.DataFrame({
        col: both[col + '_a'] - both[col + '_c'],
        key: both[key]
    })
コード例 #28
0
ファイル: test_tile_providers.py プロジェクト: zoom11jc/bokeh
 def test_attribution(self, name):
     p = bt.get_provider(getattr(bt, name))
     assert p.attribution == (
         '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors,'
         '&copy; <a href="https://cartodb.com/attributions">CartoDB</a>')
コード例 #29
0
ファイル: Game_map_plot.py プロジェクト: shihao1007/vggm
df = df.set_index('created_at')

# this map is initialized to include the whole earth
plot = figure(plot_width=1000,
              plot_height=550,
              x_range=(-20000000, 20000000),
              y_range=(-7000000, 7000000),
              x_axis_type="mercator",
              y_axis_type="mercator",
              tools="hover, pan, box_zoom, wheel_zoom, reset",
              tooltips=[('user id', '@user_id'), ('game', '@game'),
                        ('location', '@name'),
                        ('followers', '@followers_count')])

# add the tile from CARTOBPOSITRON database
CARTODBPOSITRON = get_provider(Vendors.CARTODBPOSITRON)
plot.add_tile(CARTODBPOSITRON)

# create a column data source
source = ColumnDataSource(
    data={
        'x': df.merc_x,
        'y': df.merc_y,
        'size': df.circle_size,
        'name': df.name,
        'user_id': df.tweet_user_id,
        'followers_count': df.followers_count,
        'game': df.game,
        'color': df.game_colors
    })
コード例 #30
0
ファイル: test_tile_providers.py プロジェクト: zoom11jc/bokeh
 def test_url(self, name):
     p = bt.get_provider(getattr(bt, name))
     assert p.url == _STAMEN_URLS[name]
コード例 #31
0
 def test_url(self, name) -> None:
     p = bt.get_provider(getattr(bt, name))
     assert p.url == _OSM_URLS[name]
コード例 #32
0
def sidebar():
    selectDataSource = st.sidebar.selectbox('Choose your preferred DataSource',
                                            ('-', 'John Hopkins'))
    if selectDataSource == 'John Hopkins':
        # load csv with CCSE Data
        df_confirmed_cases = pd.read_csv(
            'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv',
            error_bad_lines=False)
        df_deaths = pd.read_csv(
            'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv',
            error_bad_lines=False)
        df_recovered = pd.read_csv(
            'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv',
            error_bad_lines=False)
        selectVisualization = st.sidebar.selectbox(
            'Which visualization do you want to look at?',
            ('-', 'line chart', 'world map'))
        if selectVisualization == 'line chart':
            countryList = df_confirmed_cases['Country/Region'].tolist()
            countryList = list(set(countryList))
            countryList.sort()
            selectCountry = st.sidebar.selectbox(
                'Please choose your Country/Region', countryList)
            provinceList = df_confirmed_cases.loc[
                df_confirmed_cases['Country/Region'] ==
                selectCountry]['Province/State'].tolist()
            if provinceList != [np.nan]:
                province_available = True
                provinceList = df_confirmed_cases.loc[
                    df_confirmed_cases['Country/Region'] ==
                    selectCountry].fillna(0)['Province/State'].tolist()
                for i in range(len(provinceList)):
                    if provinceList[i] == 0:
                        provinceList[i] = selectCountry
                provinceList.sort()
                selectProvince = st.sidebar.selectbox(
                    'Please choose your Province/State', provinceList)
            else:
                province_available = False
            datestrList = list(df_confirmed_cases.loc[:, '1/22/20':])
            x = []
            for date in datestrList:
                datetime_obj = datetime.strptime(date, '%m/%d/%y')
                # datetime_obj = np.datetime64(datetime_obj)
                x.append(datetime_obj)
            p = figure(
                title='line chart',
                x_axis_label='Date',
                x_axis_type='datetime',
                # x_range = x,
                y_axis_label='Number of persons')
            ckb_cc = st.sidebar.checkbox('cofirmed cases', value=True)
            if ckb_cc:
                # st.write(df_confirmed_cases)  # just printing df - later i want to produce a chart
                if province_available == False:
                    y_cc = list(df_confirmed_cases.loc[
                        df_confirmed_cases['Country/Region'] ==
                        selectCountry].loc[:, '1/22/20':].iloc[0])
                else:
                    if selectCountry == selectProvince:
                        df_country_cc = df_confirmed_cases.loc[(
                            df_confirmed_cases['Country/Region'] ==
                            selectCountry)].fillna(selectCountry)
                        y_cc = list(df_country_cc.loc[
                            (df_country_cc['Country/Region'] == selectCountry)
                            & (df_country_cc['Province/State'] ==
                               selectProvince)].loc[:, '1/22/20':].iloc[0])
                    else:
                        y_cc = list(df_confirmed_cases.loc[
                            (df_confirmed_cases['Country/Region'] ==
                             selectCountry)
                            & (df_confirmed_cases['Province/State'] ==
                               selectProvince)].loc[:, '1/22/20':].iloc[0])
                p.line(x, y_cc, legend='confirmed cases', line_width=2)

            ckb_d = st.sidebar.checkbox('deaths', value=True)
            if ckb_d:
                # st.write(df_deaths)
                if province_available == False:
                    y_d = list(
                        df_deaths.loc[df_deaths['Country/Region'] ==
                                      selectCountry].loc[:,
                                                         '1/22/20':].iloc[0])
                else:
                    if selectCountry == selectProvince:
                        df_country_d = df_deaths.loc[(
                            df_deaths['Country/Region'] == selectCountry
                        )].fillna(selectCountry)
                        y_d = list(df_country_d.loc[
                            (df_country_d['Country/Region'] == selectCountry)
                            & (df_country_d['Province/State'] == selectProvince
                               )].loc[:, '1/22/20':].iloc[0])
                    else:
                        y_d = list(df_deaths.loc[
                            (df_deaths['Country/Region'] == selectCountry)
                            & (df_deaths['Province/State'] == selectProvince)].
                                   loc[:, '1/22/20':].iloc[0])
                p.line(x, y_d, legend='deaths', line_width=2, color='red')
            if selectCountry != 'Canada':
                ckb_r = st.sidebar.checkbox('recovered', value=True)
                if ckb_r:
                    if province_available == False:
                        y_r = list(df_recovered.loc[
                            df_recovered['Country/Region'] ==
                            selectCountry].loc[:, '1/22/20':].iloc[0])
                    else:
                        if selectCountry == selectProvince:
                            df_country_r = df_recovered.loc[(
                                df_recovered['Country/Region'] == selectCountry
                            )].fillna(selectCountry)
                            y_r = list(df_country_r.loc[(
                                df_country_r['Country/Region'] == selectCountry
                            ) & (df_country_r['Province/State'] ==
                                 selectProvince)].loc[:, '1/22/20':].iloc[0])
                        else:
                            y_r = list(df_recovered.loc[(
                                df_recovered['Country/Region'] == selectCountry
                            ) & (df_recovered['Province/State'] ==
                                 selectProvince)].loc[:, '1/22/20':].iloc[0])
                    p.line(x,
                           y_r,
                           legend='recovered',
                           line_width=2,
                           color='green')
                    # st.write(df_recovered)
            st.bokeh_chart(p)
        if selectVisualization == 'world map':
            # implemet world map visualization with circles to hover over
            selectDate = st.sidebar.date_input(
                'On which day would you like to see the map?',
                datetime.today() - timedelta(days=1))
            tile_provider = get_provider(Vendors.CARTODBPOSITRON)
            p = figure(x_range=(-17000000, 17000000),
                       y_range=(-6000000, 8000000),
                       x_axis_type="mercator",
                       y_axis_type="mercator",
                       plot_width=800,
                       plot_height=400)
            p.add_tile(tile_provider)
            for i in range(len(df_confirmed_cases)):
                lat = df_confirmed_cases.at[i, 'Lat']
                lon = df_confirmed_cases.at[i, 'Long']
                x_merc, y_merc = latlong2merc(lat, lon)
                p.circle(x=x_merc, y=y_merc, size=10, color='blue')
            st.bokeh_chart(p)
コード例 #33
0
 def test_copies(self, name) -> None:
     p1 = bt.get_provider(getattr(bt, name))
     p2 = bt.get_provider(getattr(bt, name))
     assert p1 is not p2
コード例 #34
0
ファイル: tile_smoothing.py プロジェクト: digitalsatori/Bokeh
from bokeh.layouts import column
from bokeh.plotting import figure, show, output_file
from bokeh.tile_providers import get_provider, Vendors

output_file("tile_smoothing.html")

# range bounds supplied in web mercator coordinates
p1 = figure(x_range=(-2000000, 6000000), y_range=(-1000000, 7000000),
            x_axis_type="mercator", y_axis_type="mercator", title='Smoothed')
p2 = figure(x_axis_type="mercator", y_axis_type="mercator", title='Non-smoothed')

# Link axes
p2.x_range = p1.x_range
p2.y_range = p1.y_range

# Add smoothed tiles (the default)
tile_provider = get_provider(Vendors.CARTODBPOSITRON)
r1 = p1.add_tile(tile_provider)

# Add non-smoothed tile
r2 = p2.add_tile(tile_provider, smoothing=False)

show(column(p1, p2))