Beispiel #1
0
def showViz2(gpd_city_neighborhoods, chosen_city):

    city_map = gpd_city_neighborhoods
    city_data = df_city[(df_city.City == chosen_city)]

    a = city_data.Location.apply(lambda x: x.split(', '))
    x = a.apply(lambda x: float(x[0][1:]))
    y = a.apply(lambda x: float(x[1][:-1]))
    city_data['x'] = x
    city_data['y'] = y
    geometry = [Point(xy) for xy in zip(city_data.x, city_data.y)]
    crs = city_map.crs
    city_data = GeoDataFrame(city_data, crs=crs, geometry=geometry)
    label = city_data.category.tolist()
    label_unique = list(set(label))
    print(label_unique)
    # Convert GeoDataFrames into GeoJSONDataSource objects (similar to ColumnDataSource)
    point_source = GeoJSONDataSource(geojson=city_data.to_json())
    map_source = GeoJSONDataSource(geojson=city_map.to_json())
    p = figure(title="Surveyed Coffee Shops in Chosen City (View For Density)")
    # Add the lines to the map from our GeoJSONDataSource -object (it is important to specify the columns as 'xs' and 'ys')
    p.patches('xs',
              'ys',
              source=map_source,
              color='gray',
              alpha=0.30,
              line_width=3,
              line_color="white")
    # Create color map which will be used for displaying utility scores as unique colors
    color_mapper = CategoricalColorMapper(factors=label_unique,
                                          palette=Category10[4])

    # Add the lines to the map from our 'msource' ColumnDataSource -object
    p.circle('y',
             'x',
             source=point_source,
             size=4,
             color={
                 'field': 'category',
                 'transform': color_mapper
             },
             name="foo")

    for factor, color in zip(color_mapper.factors, color_mapper.palette):
        p.circle(x=[], y=[], fill_color=color, legend=factor)

    # # Implement interactivity
    my_hover = HoverTool(names=["foo"])
    my_hover.tooltips = [('Neighborhood Name', '@Name'),
                         ('Neighborhood Category', '@category')]
    p.add_tools(my_hover)

    return p
def init_electmap_with_controls():
    print('init_electmap_with_controls()')

    merged_cnt_data = init_data()

    year_select = Slider(start=2000,
                         end=2020,
                         step=4,
                         value=2000,
                         title='Election Year')

    start = time.time()
    geo_src = GeoJSONDataSource(
        geojson=make_dataset(merged_cnt_data, year_select.value, True))
    end = time.time()
    print("geo_src time={}".format(str(end - start)))

    start = time.time()
    curr_geo_src = GeoJSONDataSource(
        geojson=make_dataset(merged_cnt_data, 2000, False))
    end = time.time()
    print("curr_geo_src time={}".format(str(end - start)))

    #slider = Slider(start=0.1, end=4, value=1, step=.1, title="power")

    callback = CustomJS(args=dict(source=geo_src, currsource=curr_geo_src),
                        code="""

    var c_data = source.data;
    var yr = cb_obj.value;

    for(var key in source.data){
      currsource.data[key] = [];
    }

    for (var i = 0; i <= source.data['YEAR'].length; i++){
        if (source.data['YEAR'][i] == yr){
            for(var key in source.data){
                currsource.data[key].push(source.data[key][i]);
            }
        }
    }

    currsource.change.emit();
    """)

    year_select.js_on_change('value', callback)

    p = make_plot(curr_geo_src)
    controls = WidgetBox(year_select)
    layout = row(p, controls)

    return layout
Beispiel #3
0
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)
Beispiel #4
0
def one_filter(plot, point_source, input_str, multi_select_proto):
    full_source = GeoJSONDataSource(geojson=point_source.geojson)
    parsed_geojson = json.loads(point_source.geojson)
    multi_select = multi_select_proto

    callback = CustomJS(args=dict(source=point_source, multi_select=multi_select, full_source=full_source, input_str = input_str), code="""
    function filter(select_vals, source, filter, full_source) {             
        for (const [key, value] of Object.entries(source.data)) {           
            while (value.length > 0) {                                      
                value.pop();                                                
            }                                                               
        }                                                                   
        for (const [key, value] of Object.entries(full_source.data)) {      
            for (let i = 0; i < value.length; i++) {                        
                if (isIncluded(filter, select_vals, i, full_source)) {      
                    source.data[key].push(value[i]);                        
                }                                                           
            }                                                               
        }                                                                   
    }                                                                       
    function isIncluded(filter, select_vals, index, full_source) {          
        for (var i = 0; i < select_vals.length; i++) {                      
            if (full_source.data[filter][index] == select_vals[i]) {        
                return true;                                                
            }                                                               
        }                                                                   
        return false;                                                       
    }                                                                       
    var select_vals = cb_obj.value;                                         
    filter(select_vals, source, input_str, full_source);           
    source.change.emit();                                                   
    """) 
    multi_select.js_on_change('value', callback)
    return multi_select
Beispiel #5
0
def test_geojson_generation():
    from bokeh.models import GeoJSONDataSource
    import json

    # pass this custom json
    test_dict = {
        "type":
        "FeatureCollection",
        "features": [{
            "id": "0",
            "type": "Feature",
            "properties": {
                "Area": "Hartlepool",
                "CRate": 377.5,
                "Cases": 352,
                "Code": "E06000001",
                "Date": "2020-06-19",
                "Deaths": 100.0,
                "IMD": 35.037,
                "IMDNorm": 0.7779257976420436,
                "MRate": "105.8",
                "MRateHighCI": "126.6",
                "MRateLowCI": "84.9",
                "testIMDLog": 0.8909381738386905,
            },
            "geometry": {
                "type": "Polygon",
                "coordinates": [[[-1.26845558516825, 54.7261163520838]]],
            },
        }],
    }
    test_json = json.dumps(test_dict)
    test_geosource = GeoJSONDataSource(geojson=test_json)
    assert (str(type(test_geosource)) ==
            "<class 'bokeh.models.sources.GeoJSONDataSource'>")
Beispiel #6
0
def mapping(thismapdf):
    thismapdf.dropna(axis='index', how='any', inplace=True)

    # npv = np.array(thismapdf['acres'])
    thismapdf['centerx'] = thismapdf.apply(lambda x: x['geometry'].centroid.x,
                                           axis=1)
    thismapdf['centery'] = thismapdf.apply(lambda x: x['geometry'].centroid.y,
                                           axis=1)

    # Expand arrays so that point density is equal to 'acres' value
    # thismapdf_expanded = pd.DataFrame(np.repeat(thismapdf.values,
    #                                             np.array(thismapdf['acres']).astype(int),
    #                                             axis=0))
    # thismapdf_expanded.columns = thismapdf.columns
    # np.repeat changed types to string, so change them back to numeric
    # thismapdf_expanded[['acres', 'centerx', 'centery']] = thismapdf_expanded[['acres', 'centerx', 'centery']].apply(
    #     pd.to_numeric)

    # npx_expanded = np.repeat(np.array(thismapdf['centerx']), npv.astype(int))
    # npy_expanded = np.repeat(np.array(thismapdf['centery']), npv.astype(int))

    geo_source_json = GeoJSONDataSource(geojson=thismapdf.to_json())

    gsource = ColumnDataSource(
        dict(x=np.array(thismapdf['centerx']),
             y=np.array(thismapdf['centery']),
             acres=np.array(thismapdf['acres']),
             LndRvrSeg=thismapdf['LndRvrSeg']))

    return thismapdf, geo_source_json, gsource
Beispiel #7
0
def plot_zones(zone, trips_origin):
    gdf = pd.merge(zone, trips_origin, left_on="id", right_on="Origin Zone ID", how='left').fillna(0)
    x_min, y_min, x_max, y_max =  gdf.total_bounds
    gs = GeoJSONDataSource(geojson=gdf.to_json())

    tile_provider = get_provider(Vendors.CARTODBPOSITRON_RETINA)

    max_trips = trips_origin.Trips.max()
    if np.isnan(max_trips) :
        max_trips = 10

    tick_labels = {v:str(int(v)) for v in np.linspace(0, max_trips+1, 8)}
    tooltips = [('id','@id'),('Trips', '@{Trips}{0,}')]


    # range bounds supplied in web mercator coordinates
    p = figure(x_range=(x_min, x_max), 
            y_range=(y_min, y_max),x_axis_type="mercator", y_axis_type="mercator", 
            x_axis_location=None, y_axis_location=None,
            plot_height=600, plot_width=900)
    p.add_tile(tile_provider)
    #Define a sequential multi-hue color palette.
    palette = brewer['RdBu'][8]

    #Instantiate LinearColorMapper that linearly maps numbers in a range, into a sequence of colors. Input nan_color.
    color_mapper = LinearColorMapper(palette = palette, low = 0, high = max_trips)
    p.patches('xs','ys', source = gs,fill_color = {'field' :'Trips', 'transform' : color_mapper},
            line_color = 'black', line_width = 0.25, fill_alpha = 0.5)

    color_bar = ColorBar(color_mapper=color_mapper, label_standoff=8,width = 800, height = 20,
                        border_line_color=None,location = (0,0), orientation = 'horizontal', major_label_overrides = tick_labels)
    p.add_layout(color_bar, 'below')
    p.add_tools(HoverTool(tooltips=tooltips,mode = 'mouse'))
    return p
Beispiel #8
0
 def get_geosource(df: gpd.GeoDataFrame) -> GeoJSONDataSource:
     """
     Convert dataframe to geojson. Define Bokeh datasource as GeoJson.
     :param df: dataframe to convert to geo source
     :return: GeoJSONDataSource
     """
     return GeoJSONDataSource(geojson=json.dumps(df.__geo_interface__))
Beispiel #9
0
def plot_geojson(zones, trips=None, plotfile=None, **figure_options):
    """Plot GeoJSON data.

    Examples:
    - plot_geojson('Manhattan')
    - plot_geojson('NYC')
    """
    p = figure(
        active_scroll="wheel_zoom",
        **figure_options,
    )
    p.toolbar.logo = None
    p.toolbar_location = "above"
    p.title.text = None

    for zone in zones:
        g = load_geojson(zone)
        geo_source = GeoJSONDataSource(geojson=json.dumps(g))
        p.patches(xs="xs", ys="ys", alpha=0.5, source=geo_source)

    if trips is not None:
        add_trips_to_plot(p, trips)

    if plotfile:
        output_file(plotfile)

    show(p)
Beispiel #10
0
def print_map(party, party_dict, grid):
    test = save_csv_of_party(party, party_dict)
    test = test.sort_values('State')
    test = test.reset_index(drop=True)
    delhi = pd.DataFrame(
        {
            "State": 'NCT of Delhi',
            "Percent": test.iloc[9]['Percent']
        },
        index=[24])
    test = test.drop([9]).reset_index(drop=True)
    test = pd.concat([test.iloc[:24], delhi,
                      test.iloc[24:]]).reset_index(drop=True)
    grid['Percent'] = test['Percent'].values
    grid['State'] = test['State'].values
    r, g, b = percent_to_color(test['Percent'].values)
    percent = rgbtohex(r, g, b)
    grid['percent'] = percent
    source = GeoJSONDataSource(geojson=grid.to_json())
    p = figure(plot_width=600, plot_height=600, output_backend="webgl")
    p.patches('xs',
              'ys',
              source=source,
              fill_color='percent',
              line_color='black',
              line_width=0.1)
    p.add_tools(
        HoverTool(tooltips=[('State', "@State"), ('Percent', '@Percent')], ))

    html = file_html(p, CDN, "Votes Percentage")
    return html
Beispiel #11
0
 def ajoute_toggle_extrémités(self) -> None:
     size = 4
     fill_color = "DarkSlateGray"
     self.g = (self.tron.set_index(
         self.tron_idx_name).geometry.boundary.dropna().explode().droplevel(
             1).rename("geometry").reset_index().reset_index())
     idx_g = self.g.columns[0]  # colonne qui contient le numéro de ligne
     self.src_extr = GeoJSONDataSource(geojson=self.g.to_json())
     self.filter_extr = IndexFilter(list(range(self.g.shape[0])))
     self.index_extrémités_par_tron = (
         self.tron.reset_index()  # numéro de ligne dans la colonne idx_g
         .merge(
             self.g, on=self.tron_idx_name
         )  # inner join donc tous les tronçons non localisés n'y sont pas
         .groupby(f"{idx_g}_x").apply(
             lambda s: list(s[f"{idx_g}_y"])).to_dict())
     view = CDSView(source=self.src_extr, filters=[self.filter_extr])
     self.extr_renderer = self.p.circle(
         x="x",
         y="y",
         size=size,
         fill_color=fill_color,
         line_color=fill_color,
         source=self.src_extr,
         visible=False,
         view=view,
     )
     self.toggle_extr = Toggle(label="Affiche les extrémités",
                               button_type="success",
                               width=100)
     self.toggle_extr.js_link("active", self.extr_renderer, "visible")
Beispiel #12
0
def make_dataset(zipcodes_to_plot, num_neighbor, period_str):
    with open('chi-zip-code-tabulation-areas-2012.geojson', 'rt') as json_file:
        chi_json = json.load(json_file)
    chi_json['features'][
        zipcodes[zipcodes_to_plot]]['properties']['color_type'] = 2

    #         print(zipcodes_to_plot)

    chi_zipcode_to_dist = pd.read_pickle('chi_zipcode_to_dist_' + period_str)

    for zipcode in zipcodes:
        if zipcode in chi_zipcode_to_dist:
            chi_json['features'][
                zipcodes[zipcode]]['properties']['has_data'] = 'YES'
        else:
            chi_json['features'][
                zipcodes[zipcode]]['properties']['has_data'] = 'NO'

    if zipcodes_to_plot in chi_zipcode_to_dist:
        distances = chi_zipcode_to_dist[zipcodes_to_plot]
        #         print (distances)
        num_neighbor_count = 0
        for neighbor_idx in range(len(distances)):
            if distances[neighbor_idx][0] in zipcodes:
                num_neighbor_count += 1
                chi_json['features'][zipcodes[distances[neighbor_idx][0]]][
                    'properties']['color_type'] = 1
            if num_neighbor_count == num_neighbor:
                break

    geojson = json.dumps(chi_json)
    geo_source = GeoJSONDataSource(geojson=geojson)
    return geo_source
Beispiel #13
0
def make_plot(d):
    TOOLTIPS=[("index", "$index"),("name", "$name")]
    p = figure(title="World Oceans", tools='pan, hover, wheel_zoom, reset')
    geosource = GeoJSONDataSource(geojson = d)
    p.patches('xs','ys', source = geosource)
    print("Plot made")
    return p
def make_plot(geo_src):
    # define color palettes
    palette = brewer["RdYlBu"][8]

    # use reverse order so higher values are darker
    palette = palette[::-1]

    # instantiate LineraColorMapper and manually set low/high end for colorbar
    color_mapper = LinearColorMapper(palette=palette, low=1, high=0)
    # #TapTool
    tap = TapTool()
    states_usa = gpd.read_file("bokeh/cb_2018_us_state_20m.shp")
    states_usa = states_usa.loc[~states_usa["NAME"].isin(["Alaska", "Hawaii"])]
    geosource_states = GeoJSONDataSource(geojson=states_usa.to_json())

    def function_geosource(attr, old, new):
        try:
            selected_index = geosource_states.selected.indices[0]
            state_name = states_usa.iloc[selected_index]['NAME']
            print(state_name)
        except IndexError:
            pass

    geosource_states.selected.on_change('indices', function_geosource)

    # create figure object
    plot = figure(
        title="Republican or Democrat Win by County in Presidential Election",
        plot_height=600,
        plot_width=950,
        toolbar_location="below",
        output_backend="webgl",
        tools="pan, wheel_zoom, reset, tap")

    plot.xgrid.grid_line_color = None
    plot.ygrid.grid_line_color = None
    plot.patches("xs",
                 "ys",
                 source=geosource_states,
                 fill_alpha=0.0,
                 line_color="#884444",
                 line_width=2,
                 line_alpha=0.3)
    # add patch renderer to figure
    counties = plot.patches("xs",
                            "ys",
                            source=geo_src,
                            fill_color={
                                'field': 'WINNING_PARTY_BINARY',
                                'transform': color_mapper
                            },
                            line_color="gray",
                            line_width=0.25,
                            fill_alpha=1)
    # create hover tool
    plot.add_tools(
        HoverTool(renderers=[counties],
                  tooltips=[("County", "@NAME"), ("Rep Votes", "@REP_VOTES"),
                            ("Dem Votes", "@DEM_VOTES")]))
    return plot
def create_interactive_map():
    prefecture_boundaries = _read_prefecture_boundaries_shapefile()
    geographic_distribution_data = _read_geographic_distribution_data(DATES)
    geo_source = GeoJSONDataSource(geojson=_merge_and_convert_to_json(
        prefecture_boundaries, geographic_distribution_data, DATES[-1]))
    _plot_choropleth(geo_source, prefecture_boundaries,
                     geographic_distribution_data)
Beispiel #16
0
 def build_data_source(self, year: int, permit_type: str):
     target_field = self.build_field(year, permit_type)
     return dict(
         target_field=target_field,
         column_data_source=GeoJSONDataSource(geojson=self.to_json()),
         min_count=self.min_max_dict[target_field][0],
         max_count=self.min_max_dict[target_field][1])
Beispiel #17
0
def visualise(graph, geo_file):
    """
    Visualisation code that uses bokeh and geometry data from a JSON file
    to represent a coloured graph.
    """

    with open(geo_file, 'r') as geo_file:
        data = json.load(geo_file)

    # Dict comprehension that creates a dictionary with a lowercase name for the
    # node if it has at least one neighbour
    states = {
        node.name.lower(): node
        for node in graph.nodes.values() if len(node.neighbours) != 0
    }

    # Take the features of the states that have at least one neighbour
    for i in range(len(data['features'])):
        data['features'] = [
            feature for feature in data['features']
            if feature['properties']['NAME'].lower().replace(' ', '') in states
        ]

    # Get the colour of the states from the corresponding nodes
    for feature in data['features']:
        if states[feature['properties']['NAME'].lower().replace(
                ' ', '')].get_value() is not None:
            feature['properties']['colour'] = states[
                feature['properties']['NAME'].lower().replace(
                    ' ', '')].get_value().colour.get_web()

            feature['properties']['cost'] = states[feature['properties']
                                                   ['NAME'].lower().replace(
                                                       ' ',
                                                       '')].get_value().value
            feature['properties']['transmitter'] = states[
                feature['properties']['NAME'].lower().replace(
                    ' ', '')].get_value().name
        else:
            feature['properties']['colour'] = 'grey'
            feature['properties']['cost'] = 0
            feature['properties']['transmitter'] = "None"

    geo_source = GeoJSONDataSource(geojson=json.dumps(data))

    # Set the bokeh tooltips
    TOOLTIPS = [("(x,y)", "($x, $y)"), ("State", "@NAME"),
                ("Transmitter", "@transmitter"), ("Cost", "@cost")]

    p = figure(background_fill_color="lightgrey", tooltips=TOOLTIPS)
    p.sizing_mode = 'scale_height'
    p.patches(xs='xs',
              ys='ys',
              fill_color='colour',
              line_color='black',
              line_width=0.2,
              source=geo_source)

    show(p)
Beispiel #18
0
def make_plot(d):
    risk = calculate_risk()
    TOOLTIPS = [("index", "$index"), ("name", "$name")]
    p = figure(title="Baltic Sea", tools='pan, hover, wheel_zoom, reset')
    geosource = GeoJSONDataSource(geojson=d)
    p.patches('xs', 'ys', source=geosource)
    print("Plot made")
    return p
def showViz1(gpd_city_neighborhoods, chosen_city):
    
    comb_gpd = gpd.GeoDataFrame(gpd_city_neighborhoods[['State','County','City','Name','geometry']].merge(df_feature[['Name','disp_score','Count']],how='inner',on='Name'))
    chosen_city_map_gpd = comb_gpd.loc[comb_gpd['City']==chosen_city]
    chosen_city_map_gpd = chosen_city_map_gpd.drop_duplicates(subset='Name', keep='first')# Drop any duplicate neighborhoods
    
    # Read the data
    main_map = gpd_city_neighborhoods
    
    # Reproject to the same coordinate system
    CRS = {'init' :'epsg:4326'}
    data=chosen_city_map_gpd
    data.crs = CRS
    main_map.crs = CRS
    
    # Convert GeoDataFrames into GeoJSONDataSource objects (similar to ColumnDataSource)
    point_source = GeoJSONDataSource(geojson=data.to_json())
    map_source = GeoJSONDataSource(geojson=main_map.to_json())
    
    # Initialize our plot figure
    p = figure(title="Neighborhood Utility Scores (Higher is better for business)")
    
    # Add the background neighborhood regions to the map from our map_source GeoJSONDataSource object
    # (it is important to specify the columns as 'xs' and 'ys')
    p.patches('xs', 'ys', source=map_source, color='gray', alpha=0.30, line_width=3,line_color = "white")
    
    # Create color map which will be used for displaying utility scores as unique colors
    color_mapper = LinearColorMapper(palette='Magma256', low=0, high=1000)
    # color_mapper = LogColorMapper(palette='Magma256', low=400, high=4000)
    
    # Add the neighborhood data to the map from the point_source ColumnDataSource object
    # (it is important to specify the columns as 'xs' and 'ys')
    p.patches('xs', 'ys', source=point_source, color={'field': 'disp_score','transform': color_mapper},
              line_width=3,line_color = "white",name="foo")
    
    # Add color bar
    color_bar = ColorBar(color_mapper=color_mapper, width=8,  location=(0,0))
    p.add_layout(color_bar, 'right')
    
    # Implement interactivity
    my_hover = HoverTool(names=["foo"])
    my_hover.tooltips = [('Neighborhood Name','@Name'),('Neighborhood Utility Score', '@disp_score'),
                         ('Number of Stores','@Count')]
    p.add_tools(my_hover)
    
    return p
def index():

    #Downloading the datasets
    import geopandas as gpd

    db_bike_path = "data/geo_export_0ff3043a-1833-476b-afe0-779dfa091ebd.shp"
    db_bike = gpd.read_file(db_bike_path)

    db_roads_path = "data/tl_2017_06075_roads.shp"
    db_roads = gpd.read_file(db_roads_path)

    #Plotting the bike lanes and the streets
    from bokeh.plotting import figure
    from bokeh.models import GeoJSONDataSource
    from bokeh.embed import components
    from bokeh.resources import INLINE
    from flask import render_template

    SF = figure(aspect_scale=1, match_aspect=True)

    db_roads_json = GeoJSONDataSource(geojson=db_roads.to_json())
    SF.multi_line('xs',
                  'ys',
                  source=db_roads_json,
                  color="gray",
                  line_width=0.5,
                  legend="All streets")

    db_bike_json = GeoJSONDataSource(geojson=db_bike.to_json())
    SF.multi_line('xs',
                  'ys',
                  source=db_bike_json,
                  color="red",
                  line_width=1.5,
                  legend="Bike Lanes")

    SF.legend.click_policy = "hide"

    #Convert the plot into HTML and JS that can be read by base.html
    script_plot, div_plot = components(SF, INLINE)

    return render_template('plot.html',
                           script=script_plot,
                           div=div_plot,
                           js_resources=INLINE.render_js(),
                           css_resources=INLINE.render_css())
    def colony_loss_map(self):
        # create color maps
        palette = Viridis[8]
        # reverse so darkest is highest
        palette = palette[::-1]
        color_mapper = LinearColorMapper(palette=palette,
                                         low=0,
                                         high=100,
                                         nan_color='#d9d9d9')
        #Create color bar.
        color_bar = ColorBar(color_mapper=color_mapper,
                             label_standoff=8,
                             width=500,
                             height=20,
                             border_line_color=None,
                             location=(0, 0),
                             orientation='horizontal')

        #Hover tool
        hover = HoverTool(tooltips=[(
            'State', '@state'), ("Winter colony loss (%)",
                                 '@colony_loss'), ('Num Colonies',
                                                   '@colonies')])

        #Create figure object.
        self.loss_plot = figure(title='Colony Loss in %d' %
                                self.all_years.max(),
                                plot_height=600,
                                plot_width=950,
                                toolbar_location=None,
                                tools=[hover])
        self.loss_plot.xgrid.grid_line_color = None
        self.loss_plot.ygrid.grid_line_color = None

        #Add patch renderer to figure.
        self.geo_source = GeoJSONDataSource(
            geojson=self.data_by_year(self.all_years.max()))
        self.loss_plot.patches('xs',
                               'ys',
                               source=self.geo_source,
                               fill_color={
                                   'field': 'colony_loss',
                                   'transform': color_mapper
                               },
                               line_color='black',
                               line_width=0.25,
                               fill_alpha=1)  # Specify figure layout.
        self.loss_plot.add_layout(color_bar, 'below')

        self.slider = Slider(title='Year',
                             start=self.all_years.min(),
                             end=self.all_years.max(),
                             step=1,
                             value=self.all_years.max())
        self.slider.on_change('value', self.updated_plot_year)

        layout = column(self.loss_plot, widgetbox(self.slider))
        return layout
Beispiel #22
0
def create_maps_for_each_year(json_data, map_json, final_color_palette):
    #Input GeoJSON source that contains features for plotting.
    geosource = GeoJSONDataSource(geojson=json_data)

    # Using the converted matplotlib colors
    final_palette = final_color_palette

    # Instantiate LinearColorMapper that linearly maps numbers in a range, into a sequence of colors.
    max_value = 25000000
    color_mapper = LinearColorMapper(palette=final_palette,
                                     low=0,
                                     high=max_value)

    # Define custom tick labels for color bar.
    tick_labels = {
        '0': '$0',
        '5000000': '$5M',
        '10000000': '$10M',
        '15000000': '$15M',
        '20000000': '$20M',
        '25000000': '$25M'
    }

    # Create color bar.
    color_bar = ColorBar(color_mapper=color_mapper,
                         label_standoff=8,
                         width=500,
                         height=20,
                         border_line_color=None,
                         location=(0, 0),
                         orientation='horizontal',
                         major_label_overrides=tick_labels)

    # Create figure object.
    p = figure(title='NYC Property Sales',
               plot_height=600,
               plot_width=600,
               toolbar_location=None)
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None

    # Add patch renderer to figure.
    p.patches('xs',
              'ys',
              source=geosource,
              fill_color={
                  'field': 'AVERAGES',
                  'transform': color_mapper
              },
              line_color='black',
              line_width=0.25,
              fill_alpha=1)

    # Specify figure layout.
    p.add_layout(color_bar, 'below')

    return p
Beispiel #23
0
def plot_gmap(zones, trips=None, **map_options):
    """Plot zones over a Google Map.

    Examples:
    - plot_gmap(['Astoria', 'Manhattan'], zoom=12)
    - plot_gmap(['Astoria', 'Midtown', 'Greenpoint', 'Sunnyside', 'Harlem'])
    """

    # Gather zone data
    polygons = [
        GeoJSONDataSource(geojson=json.dumps(load_geojson(z))) for z in zones
    ]
    u = unary_union([load_geojson(z, make_shape=True) for z in zones])
    m_polygons = u.centroid

    plot = GMapPlot(
        api_key=GOOGLE_API_KEY,
        x_range=Range1d(),
        y_range=Range1d(),
        map_options=GMapOptions(
            lat=m_polygons.y,
            lng=m_polygons.x,
            map_type="roadmap",
            **map_options,
        ),
    )
    plot.toolbar.logo = None
    plot.toolbar_location = "above"
    plot.title.text = None

    # Toolbar
    wheel_zoom = WheelZoomTool()
    plot.add_tools(
        PanTool(),
        BoxZoomTool(),
        BoxSelectTool(),
        wheel_zoom,
        ZoomInTool(),
        ZoomOutTool(),
        ResetTool(),
        SaveTool(),
    )
    plot.toolbar.active_scroll = wheel_zoom

    # Add neighborhood polygons
    for geo_source in polygons:
        glyph = Patches(xs="xs", ys="ys", fill_color="Blue", fill_alpha=0.2)
        plot.add_glyph(geo_source, glyph)

    # Add trips
    if trips is not None:
        add_trips_to_plot(plot, trips)

    output_file("plots/plot.html")
    show(plot)

    return plot
def map_plot(data, target_col, geodf):
    """
    Function enables creation of inspectable maps depicting statistical values using bokeh plotting library and geopandas to supply vector maps
    of polish regions
    data - data to use as a base for the plot
    target_col - column in supplied data with value of depicted statistic
    geodf - geopandas dataframe with vectors
    palet - color palette fro bokeh to use - color(<size of palette>)
    """

    # merging dataframes, creating source
    geodf = gpd.GeoDataFrame(geodf.merge(data, on="region")).to_json()
    source = GeoJSONDataSource(geojson=geodf)

    # defining figure
    p = figure(plot_height=500,
               plot_width=500,
               toolbar_location="below",
               sizing_mode="scale_both")
    # defining color palette
    palette = inferno(8)
    palette = palette[::-1]

    # defining color mapper to turn values into colors
    color_mapper = LinearColorMapper(palette=palette,
                                     low=0,
                                     high=max(data[target_col[0]]) * 1.1)
    # creating color bar to display below of the plot
    color_bar = ColorBar(color_mapper=color_mapper,
                         label_standoff=8,
                         border_line_color=None,
                         location=(0, 0),
                         orientation="vertical")

    # Add patch renderer to figure.
    plska = p.patches("xs",
                      "ys",
                      source=source,
                      fill_color={
                          "field": target_col[0],
                          "transform": color_mapper
                      },
                      line_color="grey",
                      line_width=0.25,
                      fill_alpha=1)
    # Create hover tool
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None
    p.axis.visible = False
    p.add_tools(
        HoverTool(renderers=[plska],
                  tooltips=[('Województwo', '@region'),
                            (target_col[1], f'@{target_col[0]}')]))

    # add color bar to the layot
    p.add_layout(color_bar, "right")
    return (p)
Beispiel #25
0
def plot_map(data):
    merged_json = json.loads(data.to_json())
    json_data = json.dumps(merged_json)

    geosource = GeoJSONDataSource(geojson=json_data)

    palette = brewer['YlGnBu'][8]
    palette = palette[::-1]

    #Define custom tick labels for color bar.
    tick_labels = {
        '0': '0%',
        '5': '5%',
        '10': '10%',
        '15': '15%',
        '20': '20%',
        '25': '25%',
        '30': '30%',
        '35': '35%',
        '40': '>40%'
    }

    color_mapper = LinearColorMapper(palette=palette, low=0, high=51)
    # color_bar = ColorBar(color_mapper=color_mapper, label_standoff=8, width=500, height=20, border_line_color=None,
    #                      location=(0, 0), orientation='horizontal', major_label_overrides=tick_labels)
    color_bar = ColorBar(color_mapper=color_mapper,
                         label_standoff=8,
                         width=500,
                         height=20,
                         border_line_color=None,
                         location=(0, 0),
                         orientation='horizontal')

    p = figure(title='Random Numbers',
               plot_height=600,
               plot_width=950,
               toolbar_location=None)

    # Add patch renderer to figure.
    p.patches(xs='xs',
              ys='ys',
              source=geosource,
              fill_color={
                  'field': 'data',
                  'transform': color_mapper
              },
              line_color='black',
              line_width=0.25,
              fill_alpha=0.8)

    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None

    p.add_layout(color_bar, 'below')

    show(p)
Beispiel #26
0
def create_geojson_feature_points(data: List[float],
                                  properties_list: List[Dict[str, str]]):
    collection = []
    for point, properties in zip(data, properties_list):
        collection.append(Feature(geometry=Point(point),
                                  properties=properties))

    feature_collection = FeatureCollection(collection)

    return GeoJSONDataSource(geojson=dumps(feature_collection))
def plot_map(dataframe, column):

    merged_json=json.loads(dataframe.to_json())
    
    json_data=json.dumps(merged_json)
    geosource = GeoJSONDataSource(geojson= json_data)
    
    palette= brewer['RdYlBu'][10]
    
    vals=dataframe[dataframe[column]>-50][column].values
    #vals=vals - np.mean(vals)
    vmin=np.round(np.min(vals), decimals = 1)
    r= np.max(vals) - np.min(vals)
    color_mapper = LinearColorMapper (palette= palette, low = vmin-5,
                                    high= vmin + r)
    tick_labels= {'no values': str(np.round((vmin-5),decimals=1)),
                '0': str(np.round(vmin,decimals=1)),
                '10': str(np.round((vmin + 0.1 * r),decimals=1)),
                '20': str(np.round((vmin + 0.2 * r),decimals=1)),
                '30': str(np.round((vmin + 0.3 * r),decimals=1)),
                '40': str(np.round((vmin + 0.4 * r),decimals=1)),
                '50': str(np.round((vmin + 0.5 * r),decimals=1)),
                '60': str(np.round((vmin + 0.6 * r),decimals=1)),
                '70': str(np.round((vmin + 0.7 * r),decimals=1)),
                '80': str(np.round((vmin + 0.8 * r),decimals=1)),
                '90': str(np.round((vmin + 0.9 * r),decimals=1)),
                '100': str(np.round((vmin + r),decimals=1))
                }
    color_bar = ColorBar(color_mapper= color_mapper, 
                        label_standoff=10, width = 500, height = 20,
                        border_line_color = None, location = (0,0), 
                        orientation='horizontal', major_label_overrides= tick_labels)
    #figure
    TOOLTIPS = [
    ("country", "@country"),
    (column, "@"+column),
    ]

    p = figure(title = ' Average Extrovertedness of each country, NOTE: countries  with value -100 do not enough values', 
            plot_height = 600 , plot_width = 950, tooltips = TOOLTIPS)
    p.xgrid.grid_line_color= None
    p.ygrid.grid_line_color = None
    p.xaxis.visible=False
    p.yaxis.visible=False
    #add patch renders to figure
    
    p.patches('xs','ys', source = geosource, fill_color = {'field': column, 'transform' : color_mapper},
            line_color = 'black', line_width = 0.25 , fill_alpha = 0.8)
    
    p.add_layout(color_bar, 'below')
    #html = file_html(p, CDN, "my plot")
    output_notebook()
    show(p)
    print("Top 10 countries in the psychometric")
    print(dataframe[['country',column]].sort_values(by=column, ascending=False).head(10))
Beispiel #28
0
def plot(ny):
    # Input GeoJSON source that contains features for plotting
    ny_source = GeoJSONDataSource(geojson=ny.to_json())
    # Define color palettes
    palette = brewer['OrRd'][8]
    palette = palette[::
                      -1]  # reverse order of colors so higher values have darker colors
    # Instantiate LinearColorMapper that linearly maps numbers in a range, into a sequence of colors.
    color_mapper = LinearColorMapper(palette=palette,
                                     low=ny['Points'].min(),
                                     high=ny['Points'].max())

    # Create color bar.
    color_bar = ColorBar(color_mapper=color_mapper,
                         label_standoff=8,
                         width=500,
                         height=20,
                         border_line_color=None,
                         location=(0, 0),
                         orientation='horizontal')

    # Create figure object.
    p = figure(title='Calculated Weighted Points',
               plot_height=650,
               plot_width=950,
               toolbar_location='below',
               tools="pan, wheel_zoom, box_zoom, reset",
               output_backend="webgl")
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None
    # Add patch renderer to figure.
    states = p.patches('xs',
                       'ys',
                       source=ny_source,
                       fill_color={
                           'field': 'Points',
                           'transform': color_mapper
                       },
                       line_color="gray",
                       line_width=0.25,
                       fill_alpha=1)
    # Create hover tool
    p.add_tools(
        HoverTool(renderers=[states],
                  tooltips=[('PO Name', '@PO_NAME'), ('Points', '@Points')]))

    color_bar = ColorBar(color_mapper=color_mapper,
                         label_standoff=8,
                         width=950,
                         height=20,
                         border_line_color=None,
                         location=(0, 0),
                         orientation='horizontal')
    p.add_layout(color_bar, 'below')
    show(p)
    def to_geo_json_data_source(data: gpd.geodataframe.GeoDataFrame) -> GeoJSONDataSource:
        """Convert the data to a GeoJSONDataSource

        Args:
            data (gpd.geodataframe.GeoDataFrame): The data

        Returns:
            GeoJSONDataSource: The resulting GeoJson Data
        """
        json_data = json.dumps(json.loads(data.to_json()))
        return GeoJSONDataSource(geojson=json_data)
Beispiel #30
0
def create_map_plot(map_source):
    if map_source:
        colors = brewer['RdBu'][9]
        with open(
                os.path.join(os.path.dirname(__file__),
                             'data/countries.geo.json'), "r") as f:
            countries = GeoJSONDataSource(geojson=f.read())

        cube_data = map_source.data['cube_data'][0]
        lons = map_source.data['lons'][0]
        lats = map_source.data['lats'][0]
        # Set up plot
        x_range = (-180, 180)  # could be anything - e.g.(0,1)
        y_range = (-90, 90)

        # plot = figure(plot_height=49, plot_width=360, x_range=x_range, y_range=y_range)
        # plot = figure(plot_height=300, plot_width=600, x_range=x_range, y_range=y_range)
        mplot = figure(plot_height=600,
                       plot_width=1200,
                       x_range=x_range,
                       y_range=y_range,
                       tools=["pan, reset, save, wheel_zoom, hover"],
                       title='Annual Mean Temperature anomaly (C)',
                       x_axis_label='Longitude',
                       y_axis_label='Latitude')  #, aspect_ratio=2)
        color_mapper_z = LinearColorMapper(palette=colors, low=-3, high=3)
        mplot.image(image='cube_data',
                    x=min(lons),
                    y=min(lats),
                    dw=max(lons) - min(lons),
                    dh=max(lats) - min(lats),
                    source=map_source,
                    color_mapper=color_mapper_z)

        # add titles
        mplot.text(0,
                   -60,
                   'label',
                   source=map_source,
                   text_color="firebrick",
                   text_align="center",
                   text_font_size="35pt",
                   text_alpha=0.5)

        color_bar = ColorBar(color_mapper=color_mapper_z, location=(0, 0))

        mplot.patches("xs",
                      "ys",
                      color=None,
                      line_color="grey",
                      source=countries,
                      alpha=0.5)
        mplot.add_layout(color_bar, 'right')
        return mplot