예제 #1
0
def create_plot(center_coords, zoom_level=8):

    x_range = Range1d()
    y_range = Range1d()

    # JSON style string taken from: https://snazzymaps.com/style/1/pale-dawn
    map_options = GMapOptions(lat=center_coords['lat'],
                              lng=center_coords['lng'],
                              map_type="roadmap",
                              zoom=zoom_level,
                              styles="""
    [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2e5d4"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#c5dac6"}]},{"featureType":"poi.park","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":20}]},{"featureType":"road","elementType":"all","stylers":[{"lightness":20}]},{"featureType":"road.highway","elementType":"geometry","stylers":[{"color":"#c5c6c6"}]},{"featureType":"road.arterial","elementType":"geometry","stylers":[{"color":"#e4d7c6"}]},{"featureType":"road.local","elementType":"geometry","stylers":[{"color":"#fbfaf7"}]},{"featureType":"water","elementType":"all","stylers":[{"visibility":"on"},{"color":"#acbcc9"}]}]
    """)

    plot = GMapPlot(x_range=x_range,
                    y_range=y_range,
                    map_options=map_options,
                    title=u"Тверь")

    pan = PanTool()
    wheel_zoom = WheelZoomTool()
    box_select = BoxSelectTool()

    plot.add_tools(pan, wheel_zoom, box_select)
    return plot
예제 #2
0
def trail_map(data):
    lon = (min(data.lon) + max(data.lon)) / 2
    lat = (min(data.lat) + max(data.lat)) / 2

    map_options = GMapOptions(lng=lon, lat=lat, zoom=13)
    plot = GMapPlot(plot_width=800,
                    plot_height=800,
                    map_options=map_options,
                    api_key=API_KEY)
    plot.title.text = "%s - Trail Map" % name
    plot.x_range = Range1d()
    plot.y_range = Range1d()
    plot.add_tools(PanTool(), WheelZoomTool(), ResetTool())

    line_source = ColumnDataSource(dict(x=data.lon, y=data.lat,
                                        dist=data.dist))
    line = Line(x="x", y="y", line_color="blue", line_width=2)
    plot.add_glyph(line_source, line)

    if plot.api_key == "GOOGLE_API_KEY":
        plot.add_layout(
            Label(x=240,
                  y=700,
                  x_units='screen',
                  y_units='screen',
                  text='Replace GOOGLE_API_KEY with your own key',
                  text_color='red'))

    return plot
예제 #3
0
def showmap():
    tools = "pan,wheel_zoom,box_zoom,reset,save,hover,zoom_in,box_edit,poly_draw"
    # tools = " box_edit, box_select, box_zoom, click, crosshair, help, hover, lasso_select, pan, point_draw, poly_draw, poly_edit, poly_select, previewsave, redo, reset, save, tap, undo, wheel_zoom, xbox_select, xbox_zoom, xpan, xwheel_pan, xwheel_zoom, xzoom_in, xzoom_out, ybox_select, ybox_zoom, ypan, ywheel_pan, ywheel_zoom, yzoom_in, yzoom_out, zoom_in"
    map_options = GMapOptions(lat=0.3476,
                              lng=32.5825,
                              map_type="roadmap",
                              zoom=13)
    GOOGLE_API_KEY = "AIzaSyAFCR-n7VxtftzPKR4gCje1T-cAxQXn7S8"
    plot = gmap(GOOGLE_API_KEY,
                map_options,
                tools=tools,
                title="Crimes visualizing center",
                height=700,
                width=1100)
    latitude_list, longitude_list, colors_list = get_co_ordinates()
    source = ColumnDataSource(
        data=dict(lat=latitude_list, lon=longitude_list, color=colors_list))
    plot.circle(x="lon",
                y="lat",
                size=15,
                fill_color="color",
                fill_alpha=0.8,
                source=source)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    storage_path = os.path.join(BASE_DIR, 'pathfinder/templates/pages')
    map_path = os.path.join(storage_path, 'gmap_plot.html')
    output_file(map_path)
    print("saved...")
    save(plot)
예제 #4
0
파일: plot.py 프로젝트: iitzex/flyer
def bokeh_draw(lat, lon, callsign, t):
    m = GMapOptions(lat=25.084, lng=121.23, map_type="roadmap", zoom=14)
    plot = GMapPlot(x_range=Range1d(), y_range=Range1d(), map_options=m)
    plot.title.text = t
    plot.api_key = "AIzaSyCa4x7OjPPqH9Jt9_EFHbISoUZo6cRIo7Q "

    source = ColumnDataSource(
        data=dict(
            lat=lat,
            lon=lon,
            callsign=callsign,
        ))

    circle = Circle(
        x='lon',
        y='lat',
        size=4,
        fill_color="red",
        fill_alpha=0.8,
        line_color=None)
    plot.add_glyph(source, circle)

    labels = LabelSet(
        x='lon',
        y='lat',
        text='callsign',
        text_font_size='8pt',
        level='glyph',
        x_offset=1,
        y_offset=1,
        source=source,
        render_mode='canvas')
    plot.add_layout(labels)

    export_png(plot, filename='screenshots/' + t + '.png')
예제 #5
0
def create_map():
    z = zoom.value
    lt = lat.value
    lg = lon.value
    day = mapping_day(days_options.active)
    hour = mapping_hour(slider.value)
    df['checkin_at_hour'] = checkin_at_hour(
        day,
        hour)  # adds column df['checkin_at_hour'] for use in size calculation

    sz = sizes(df['checkin_at_hour'], z)
    df['flag_1'] = selection_1(neighborhood.value)
    df['flag_2'] = selection_2(ambience.value)
    df['flag_3'] = selection_3(alcohol.value)
    df['flag_4'] = selection_4(category.value)
    df['flag_5'] = agg_selection(df['flag_1'], df['flag_2'], df['flag_3'],
                                 df['flag_4'])
    clr = colors(df['flag_5'])
    alp = alpha(df['flag_5'])

    map_options = GMapOptions(lat=lt, lng=lg, map_type="roadmap", zoom=z)
    bus_hover = HoverTool(tooltips=[('Business Name', '@name'),
                                    ('Reviews', '@review_count'),
                                    ('Checkins', '@checkin_at_hr')],
                          names=["bus_hover"])

    p = gmap("AIzaSyAQBImT1FpLK1aQvKq1e-Cfs1xd_NzC0mY",
             map_options,
             title="Vegas businesses",
             plot_width=550,
             plot_height=550,
             tools=[bus_hover, 'reset', 'pan', 'lasso_select'],
             toolbar_location="above")

    source = ColumnDataSource(data=dict(lat=df['latitude'],
                                        lon=df['longitude'],
                                        size=sz,
                                        color=clr,
                                        alpha=alp,
                                        name=df['name'],
                                        review_count=df['review_count'],
                                        checkin_at_hr=df['checkin_at_hour']))

    p.circle(x="lon",
             y="lat",
             size="size",
             fill_alpha="alpha",
             fill_color="color",
             name="bus_hover",
             line_width=1,
             line_alpha=0,
             hover_alpha=1.0,
             source=source)
    p.outline_line_alpha = 0
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None
    p.xaxis.visible = False
    p.yaxis.visible = False

    return p
예제 #6
0
 def make_plot(src):
     path = '../data/'
     with open(path + 'client_secret.json') as f:
         data = json.load(f)
     api_key = data['google_api_key']
     map_options = GMapOptions(lat=40.76,
                               lng=-73.95,
                               map_type='roadmap',
                               zoom=12,
                               styles=map_style)
     call_map = gmap(api_key,
                     map_options,
                     title='311 Calls by Location',
                     plot_width=850,
                     plot_height=850)
     call_map.circle(x='lon_round',
                     y='lat_round',
                     size='sizes',
                     source=src,
                     fill_alpha=0.8,
                     fill_color='tomato',
                     line_color='firebrick')
     hover = HoverTool(tooltips=[(
         'Longitude',
         '@lon_round{0.0}'), ('Latitude',
                              '@lat_round{0.0}'), ('Calls', '@count{0,0}')])
     call_map.add_tools(hover)
     call_map = style(call_map)
     return call_map
예제 #7
0
def geo_tab(df):
    df_sample = df.sample(
        frac=.25)  # Show 25% of the records, otherwise the map will be slow.
    map_options = GMapOptions(lat=47.335728,
                              lng=4.115118,
                              map_type="roadmap",
                              zoom=5)

    api_key = "AIzaSyAhJoQsJr9IdsbXthpM4i84HsYvJtXxLXc"

    # Output backend WebGL for better performance.
    p = gmap(api_key,
             map_options,
             title="Review Locations",
             output_backend="webgl")

    data = dict(lat=df_sample['lat'], lon=df_sample['lng'])

    p.circle(x="lon",
             y="lat",
             size=12,
             fill_color="blue",
             fill_alpha=0.8,
             source=data)

    tab = Panel(child=p, title='Review Locations')
    return tab
예제 #8
0
def main():

    map_options = GMapOptions(lat=49.2081,
                              lng=10.7394,
                              map_type='roadmap',
                              zoom=11)
    fig = gmap(
        GOOGLE_API_KEY,
        map_options,
        title='',
    )

    # tile_provider = get_provider('CARTODBPOSITRON')
    # fig = figure(
    #     x_axis_type='mercator', y_axis_type='mercator',
    # )
    # fig.add_tile(tile_provider)

    fig.width = PLOT_WIDTH
    fig.height = 700

    source = setup_source()

    circle = Circle(x='lon',
                    y='lat',
                    size=15,
                    fill_color='blue',
                    fill_alpha=0.8)
    fig.add_glyph(source, circle)

    return components(fig)
예제 #9
0
 def create_all(self):
     """
     Creates a map with all incident reports plotted onto a google maps
     of Seattle. The map is interactive, and the output file is an HTML
     document "gmap.html"
     """
     output_file("gmap.html")
     map_options = GMapOptions(lat=47.608013,
                               lng=-122.335167,
                               map_type="roadmap",
                               zoom=12)
     p = gmap("AIzaSyCaSPqCN6IgZb_vqQZ0F10LmiyK_QXd5sM",
              map_options,
              title="Seattle",
              plot_width=1000,
              plot_height=1000)
     for streets in self._df["address"].unique():
         is_street = self._df["address"] == streets
         latitude = self._df[is_street].loc[:, "latitude"]
         longitude = self._df[is_street].loc[:, "longitude"]
         source = ColumnDataSource(
             data=dict(lat=[latitude], lon=[longitude]))
         p.circle(x="lon",
                  y="lat",
                  size=10,
                  fill_color="blue",
                  fill_alpha=0.8,
                  source=source)
     show(p)
    def main_map(self):
        #code for main page map
        for i in range(len(self.titles)):
            self.data_dict[self.titles[i]]=self.color_dict[i]
            
        for k in self.topics:
            if k in self.data_dict:
                self.color_main.append(self.data_dict[k])

        map_options = GMapOptions(lat=23.3468, lng=78.5827, map_type='roadmap', zoom=5)

        my_hover = HoverTool()
        plot = GMapPlot(x_range=Range1d(), y_range=Range1d(), map_options=map_options)
        plot.title.text = "Tweet Data Analysis"
        plot.api_key = "AIzaSyAcvz_u0fGAyBE13pAnntsA1fn7Tu54RTU"

        source = ColumnDataSource(data=dict(lat=self.coord_x,lon=self.coord_y,colors=self.color_main[:len(self.coord_x)],tp=self.topics,tw=self.tweets))
        my_hover.tooltips = [('Topic','@tp'),('Tweet','@{tw}')]

        circle = Circle(x="lon", y="lat", size=8, fill_color="colors", fill_alpha=0.7, line_color=None)
        plot.add_glyph(source, circle)
        plot.add_tools(my_hover)
        plot.add_tools( WheelZoomTool(), PanTool(), ResetTool())
        output_file("F:\Final Year Project\Visualization\Website\static\main_page\map.html")
        save(obj=plot, filename="F:\Final Year Project\Visualization\Website\static\main_page\map.html")
예제 #11
0
def initiate_guest_view(api_key, map_start=c.ADDRESS):
    """
    Generates and updates visualization layout for guest users

    :params api_key string:
    :params map_start string:
    """

    # Centers map and plots listing locations
    city_lat, city_long = get_city_location(map_start, api_key)
    map_options = GMapOptions(lat=city_lat,
                              lng=city_long,
                              map_type='roadmap',
                              zoom=11)
    plt = gmap(api_key, map_options, title=map_start)
    plt.circle(x=c.LONGITUDE,
               y=c.LATITIUDE,
               size=4,
               fill_color=c.PRICE_COLOR,
               fill_alpha=0.8,
               source=SOURCE,
               legend=c.PRICE_VALUE)

    # Configures hover display
    tooltips = [('Price', '$' + '@price'),
                ('Valued at', '$' + '@predicted_price'.split('.')[0]),
                ('Value', '@price_value'), ('Sentiment Score', '@sentiment')]
    plt.add_tools(HoverTool(tooltips=tooltips))

    guest_layout = layout([[WIDGETS_GUEST, plt]], sizing_mode=c.STRETCH_BOTH)
    curdoc().clear()
    curdoc().add_root(guest_layout)
예제 #12
0
    def interactive_map(self, doc_id, db_name):
        Gmap_API_key = 'AIzaSyBL5mv0DEHyXuopWAqQ532y_JuEACbqfko'
        # retrieve data from db
        data = self.retrieve_data(doc_id=doc_id, db_name=db_name)

        style_str = """[{"featureType":"all","elementType":"geometry.fill","stylers":[{"weight":"2.00"}]},{"featureType":"all","elementType":"geometry.stroke","stylers":[{"color":"#9c9c9c"}]},{"featureType":"all","elementType":"labels.text","stylers":[{"visibility":"on"}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2f2f2"}]},{"featureType":"landscape","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"landscape.man_made","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":-100},{"lightness":45}]},{"featureType":"road","elementType":"geometry.fill","stylers":[{"color":"#eeeeee"}]},{"featureType":"road","elementType":"labels.text.fill","stylers":[{"color":"#7b7b7b"}]},{"featureType":"road","elementType":"labels.text.stroke","stylers":[{"color":"#ffffff"}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#46bcec"},{"visibility":"on"}]},{"featureType":"water","elementType":"geometry.fill","stylers":[{"color":"#c8d7d4"}]},{"featureType":"water","elementType":"labels.text.fill","stylers":[{"color":"#070707"}]},{"featureType":"water","elementType":"labels.text.stroke","stylers":[{"color":"#ffffff"}]}]"""
        AUS_BOUND_BOX = (113.338953078, -43.6345972634, 153.569469029, -10.6681857235)
        map_options = GMapOptions(lat=-28.7, lng=133.9, map_type="terrain", zoom=4, styles=style_str)

        plot = GMapPlot(map_options=map_options, api_key=Gmap_API_key, plot_height=450, plot_width=666)  # h:573  w:925

        for each in data['data']:
            if AUS_BOUND_BOX[0] <= each['coordinates'][0] <= AUS_BOUND_BOX[2] and \
                    AUS_BOUND_BOX[1] <= each['coordinates'][1] <= AUS_BOUND_BOX[3]:
                if each['sentiment'] >= 0.05:
                    circle = Circle(x=each['coordinates'][0], y=each['coordinates'][1], size=5, fill_color='green')
                    plot.add_glyph(circle)
                elif -0.05 < each['sentiment'] < 0.05:
                    circle = Circle(x=each['coordinates'][0], y=each['coordinates'][1], size=5, fill_color='blue')
                    plot.add_glyph(circle)
                elif each['sentiment'] <= -0.05:
                    circle = Circle(x=each['coordinates'][0], y=each['coordinates'][1], size=5, fill_color='red')
                    plot.add_glyph(circle)

        # add interactive tools
        pan = PanTool()
        wheel_zoom = WheelZoomTool()
        reset = ResetTool()
        save = SaveTool()
        plot.add_tools(pan, wheel_zoom, reset, save)

        # interactive Hover -- to be added

        script_map, div_map = components(plot)
        return script_map, div_map
예제 #13
0
def Dibujar_Grafo_Camino(lati, loni, camlat, camlon):
    output_file("gmap.html")
    map_options = GMapOptions(lat=lati[0],
                              lng=loni[0],
                              map_type="roadmap",
                              zoom=5)
    # For GMaps to function, Google requires you obtain and enable an API key:
    #
    #     https://developers.google.com/maps/documentation/javascript/get-api-key
    #
    # Replace the value below with your personal API key:
    p = gmap("AIzaSyDf3f-fQDqjQo1Dr5WSO0FDO_nM-HA3qV4",
             map_options,
             title="Austin")
    #IMPORTANTE: Profesor, si cuenta con algun error al momento de visualizar el grafico, por favor
    #coloque su API key personal como primer parametro de la función que se esta llamando en la linea
    #de codigo anterior.
    source = ColumnDataSource(data=dict(lat=lati, lon=loni))
    source2 = ColumnDataSource(data=dict(lat=camlat, lon=camlon))
    p.circle(x="lon",
             y="lat",
             size=7,
             fill_color="blue",
             fill_alpha=0.8,
             source=source)
    p.circle(x="lon",
             y="lat",
             size=10,
             fill_color="red",
             fill_alpha=0.8,
             source=source2)
    p.line(camlon, camlat, line_color="red")
    show(p)
예제 #14
0
def create_heatmap(station_scores, plot_width=1000, plot_height=600):
    map_options = GMapOptions(lat=32.06, lng=34.87, map_type="roadmap", zoom=9)
    cmap = plt.get_cmap('jet')
    plot = GMapPlot(x_range=DataRange1d(),
                    y_range=DataRange1d(),
                    map_options=map_options,
                    title="Israel")
    plot.plot_width = plot_width
    plot.plot_height = plot_height
    lat_vec = list(map(lambda x: get_loc_by_id(x).lat, station_scores.keys()))
    lon_vec = list(map(lambda x: get_loc_by_id(x).lon, station_scores.keys()))

    for ind, station in enumerate(station_scores):

        source = ColumnDataSource(data=dict(
            lat=[lat_vec[ind]],
            lon=[lon_vec[ind]],
        ))
        cmap_indx = int(station_scores[station] * cmap.N)
        cmap_val = tuple(np.floor(255 * np.array(cmap(cmap_indx)[:3])))
        circle = Circle(x="lon",
                        y="lat",
                        size=17,
                        fill_color=cmap_val,
                        fill_alpha=0.95,
                        line_color=None)
        plot.add_glyph(source, circle)

    plot.add_tools(PanTool(), WheelZoomTool())
    output_file("Mean Time to Tel-Aviv Hashalom.html")
    show(plot)
def plot(lat, lng, zoom=17, map_type='roadmap'):

    from bokeh.io import show
    from bokeh.plotting import gmap
    from bokeh.models import GMapOptions
    bokeh_width, bokeh_height = 1000, 600
    api_key = "AIzaSyB4y5u1q0_-4kVQpSMGkH_dxpnzn8PL-dQ"

    gmap_options = GMapOptions(lat=lat, lng=lng, map_type=map_type, zoom=zoom)
    p = gmap(api_key,
             gmap_options,
             title='Pays de Gex',
             width=bokeh_width,
             height=bokeh_height)
    # beware, longitude is on the x axis ;-)
    center = p.circle([lng], [lat], size=10, alpha=0.5, color='yellow')

    car_coords, car_coords_x, car_coords_y, red_x, red_y = vehicle_dots()
    # print(car_coords)
    # see how we set radius instead of size:
    center = p.circle(car_coords_x,
                      car_coords_y,
                      size=10,
                      alpha=0.5,
                      color='blue')
    center = p.circle(red_x, red_y, size=10, alpha=0.5, color='red')

    return p
예제 #16
0
def plotthis():
    map_options = GMapOptions(lat=67.97,
                              lng=-97.73,
                              map_type="roadmap",
                              zoom=2)

    plot = GMapPlot(x_range=DataRange1d(),
                    y_range=DataRange1d(),
                    map_options=map_options,
                    title="Runners IOS")

    df = pd.read_csv("runners.csv")
    df = df.dropna()
    df = df.head(500)
    source = ColumnDataSource(data=dict(
        lat=df["start_latitude"],
        lon=df["start_longitude"],
    ))

    #source = ColumnDataSource( data=dict(lat=[30.29, 30.20, 30.29],lon=[-97.70, -97.74, -97.78],))

    circle = Circle(x="lon",
                    y="lat",
                    size=15,
                    fill_color="blue",
                    fill_alpha=0.8,
                    line_color=None)
    plot.add_glyph(source, circle)

    plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool())
    output_file("gmap_plot.html")
    show(plot)
예제 #17
0
def mapOut(gmap_api, long, la):
    output_file("gmap.html")
    map_options = GMapOptions(lat=42.35,
                              lng=-71.1,
                              map_type="roadmap",
                              zoom=11)

    # For GMaps to function, Google requires you obtain and enable an API key:
    #
    #     https://developers.google.com/maps/documentation/javascript/get-api-key
    #
    # Replace the value below with your personal API key:
    p = gmap(gmap_api,
             map_options,
             title="All restarants serves pizza in Boston")

    source = ColumnDataSource(data=dict(lat=la, lon=long))

    p.circle(x="lon",
             y="lat",
             size=15,
             fill_color="blue",
             fill_alpha=0.8,
             source=source)

    show(p)
예제 #18
0
def map(request):

    map_options = GMapOptions(lat=30.2861,
                              lng=-97.7394,
                              map_type="roadmap",
                              zoom=11)
    # init scatter plot
    api_key = settings.GOOGLE_API_KEY
    bokehAx = bp.gmap(api_key, map_options, title="Austin")

    source = ColumnDataSource(data={
        'lat': [30.29, 30.20, 30.29],
        'lon': [-97.70, -97.74, -97.78]
    })

    bokehAx.circle(x="lon",
                   y="lat",
                   size=15,
                   fill_color="blue",
                   fill_alpha=0.8,
                   source=source)

    # labels etc
    #bokehAx.title.text = ''
    #bokehAx.xaxis.axis_label = 'lat'
    #bokehAx.yaxis.axis_label = 'lon'
    plotResponse = file_html(bokehAx, CDN, 'map')

    return HttpResponse(plotResponse)
예제 #19
0
def get_Gmap_options():
    """
    Generates the map options for the Google Map-Bokeh implentation. 

    Parameters
    ----------

    None. 

    Returns
    ----------

    map_options: Bokeh `GMapOptions` class.
        Options that define the Google Map region Bokeh will plot.
    """

    Australia_lat = -27.46749  # Coords the map is centred on.
    Australia_lon = 133.02809

    map_options = GMapOptions(lat=Australia_lat,
                              lng=Australia_lon,
                              map_type="roadmap",
                              zoom=4)

    return map_options
예제 #20
0
    def create_map_plot(self):
        lat = 39.8282
        lng = -98.5795
        zoom = 6
        xr = Range1d()
        yr = Range1d()
        x_range = xr
        y_range = yr
        #map_options = GMapOptions(lat=39.8282, lng=-98.5795, zoom=6)
        map_options = GMapOptions(lat=lat, lng=lng, zoom=zoom)
        #map_options = GMapOptions(lat=30.2861, lng=-97.7394, zoom=15)
        plot = GMapPlot(x_range=x_range,
                        y_range=y_range,
                        map_options=map_options,
                        plot_width=680,
                        plot_height=600,
                        title=" ")
        plot.map_options.map_type = "hybrid"
        xaxis = LinearAxis(axis_label="lon",
                           major_tick_in=0,
                           formatter=NumeralTickFormatter(format="0.000"))
        plot.add_layout(xaxis, 'below')
        yaxis = LinearAxis(axis_label="lat",
                           major_tick_in=0,
                           formatter=PrintfTickFormatter(format="%.3f"))
        plot.add_layout(yaxis, 'left')

        self.plot = plot
예제 #21
0
def get_map_plot(source, source_elog, source_radius_circle):

    #define maps, options
    map_options = GMapOptions(lat=51.4416, lng=5.4697, map_type="terrain", zoom=12)
    plot = GMapPlot(x_range=Range1d(), y_range=Range1d(), map_options=map_options)

    # use your api key below
    plot.api_key = get_api_key()

    ########################################################################
    # Define glyphs
    ########################################################################

    # triangle glyphs on the map
    triangle_event = Triangle(x="lon", y="lat", size=12, fill_color="red", fill_alpha=0.5, line_color=None, name="events")
    glyph_triangle = plot.add_glyph(source, triangle_event, nonselection_glyph=triangle_event)

    # circle glyphs on the map
    circle_elog = Circle(x="lon_elog", y="lat_elog", size=12, fill_color="color",
    fill_alpha=0.8, line_color=None, name="elog_locations")
    glyph_circle = plot.add_glyph(source_elog, circle_elog, nonselection_glyph=circle_elog, )

    circle_radius = Circle(x="lon_radius", y="lat_radius", radius= "rad_radius", fill_alpha=0.3, line_color='black')
    glyph_circle_radius = plot.add_glyph(source_radius_circle, circle_radius)

    ########################################################################
    # Other misc tools: hovers, taps, etc
    ########################################################################

    # tools to include on the visualization
    plot.add_tools(PanTool(), WheelZoomTool(),
    	    ResetTool(), TapTool())

    # Hover tool for triangles
    triangle_hover = HoverTool(renderers=[glyph_triangle],
                             tooltips=OrderedDict([
                                 ("Location", "@city"),
                                 ("Date", "@dates"),
                                 ("Problem", "@issue")
                             ]))
    plot.add_tools(triangle_hover)

    # Hover tool for circles
    circle_hover = HoverTool(renderers=[glyph_circle],
                             tooltips=OrderedDict([
                                 ("Place", "@place_elog"),
                                 ("Usage", '@value_elog'),
                                 ("Classification", '@classes')
                             ]))
    plot.add_tools(circle_hover)

    # Add legend
    legend = Legend(items=[
        LegendItem(label="elog_locations"   , renderers=[glyph_circle]),
        LegendItem(label="events" , renderers=[glyph_triangle])
    ], orientation="vertical", click_policy="hide")
    plot.add_layout(legend, "center")

    return glyph_circle, plot
예제 #22
0
def cities_visualization():
	scale = 5
	lat_tpl=()
	long_tpl=()
	cities_tpl=()
	'''
		create a dataframe without null row or column values 
	'''
	halfComplete_dataFrame= df1[df1['City, State'].str.contains(',', na=False)]

	cities_dataFrame=pd.DataFrame(halfComplete_dataFrame['City, State'])
	cities_dataFrame=cities_dataFrame.rename(columns={'City, State':'City'})
	top_cities_dataFrame=cities_dataFrame.groupby(['City']).size().reset_index().rename(columns={0:'count'})
	top_ten_cities_dataFrame=top_cities_dataFrame.sort_values(by='count', ascending=False).head(10)

	geolocator = Nominatim()


	lat_long_list=[]
	for row in top_ten_cities_dataFrame['City']:
		topTenCitiesList.append(str(row))
	#print topTenCitiesList

	
	for row in top_ten_cities_dataFrame['count']:
    		topTenCitiesCount.append(row)
    	
		
	#print topTenCitiesCount
	
	for i,val in enumerate(topTenCitiesList):
		loc=geolocator.geocode(val)
		#cities_tpl=cities_tpl+(val,)
		#long_tpl=long_tpl+(loc.longitude,)
		#lat_tpl=lat_tpl+(loc.latitude,)
		city_lat_list.append(loc.latitude)
		city_long_list.append(loc.longitude)

	#print topTenCitiesList
	#print topTenCitiesCount
	#print city_lat_list
	#print city_long_list
	#print cities_tpl
	map_options = GMapOptions(lat=39.8282, lng=-98.5795, map_type="roadmap", zoom=5)
	plot = GMapPlot(
    x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, plot_width=1100, plot_height=800)
	plot.title.text = "Top ten cities"
	plot.api_key = "AIzaSyBfcQ8lTsXC5du_Mj0IyFLuXepDt_Euawo"
	source = ColumnDataSource(
    data=dict(
        lat=city_lat_list,
        lon=city_long_list,
		#text=topTenCitiesList,
    ))
	circle = Circle(x="lon", y="lat", tags=topTenCitiesList, size=15, fill_color="blue", fill_alpha=0.8, line_color=None)
	plot.add_glyph(source, circle)
	plot.add_tools(PanTool(), WheelZoomTool(), BoxSelectTool())
	output_file("gmap_plot.html")
	show(plot)
예제 #23
0
def create_plot(fn):
    output_file(fn+'.html',title='Austin Home Prices')
    map_options = GMapOptions(lat=30.29, lng=-97.73, map_type="roadmap", zoom=11)
    plot = GMapPlot(
        x_range=DataRange1d(), y_range=DataRange1d(), map_options=map_options, title="Austin",
        api_key='AIzaSyDfPR-VHUVIr3veDt-GKNZOpHyew6TER6Q'
    )
    return plot
예제 #24
0
def make_plot(field_name):
    # Set the format of the colorbar
    min_range = format_df.loc[format_df['field'] == field_name,
                              'min_range'].iloc[0]
    max_range = format_df.loc[format_df['field'] == field_name,
                              'max_range'].iloc[0]
    field_format = format_df.loc[format_df['field'] == field_name,
                                 'format'].iloc[0]

    # Instantiate LinearColorMapper that linearly maps numbers in a range, into a sequence of colors.
    color_mapper = LinearColorMapper(palette=palette,
                                     low=min_range,
                                     high=max_range)

    # Create color bar.
    format_tick = NumeralTickFormatter(format=field_format)
    color_bar = ColorBar(color_mapper=color_mapper,
                         label_standoff=6,
                         formatter=format_tick,
                         border_line_color=None,
                         location=(0, 0))

    # Create figure object.
    map_options = GMapOptions(lat=43.60, lng=1.44, map_type="roadmap", zoom=12)

    verbage = format_df.loc[format_df['field'] == field_name,
                            'verbage'].iloc[0]

    p = gmap(GOOGLE_API_KEY,
             map_options,
             title=verbage +
             ' by Neighborhood for Apartments for Rent in Toulouse (2020)',
             plot_height=650,
             plot_width=850,
             toolbar_location="below")
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = None
    p.axis.visible = False

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

    # Specify color bar layout.
    p.add_layout(color_bar, 'right')

    # Add the hover tool to the graph
    p.add_tools(hover)
    return p
예제 #25
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
예제 #26
0
def create_map():
    z = zoom.value
    lt = lat.value
    lg = lon.value
    day = mapping_day(days_options.active)
    hour = mapping_hour(slider.value)
    df['checkin_at_hour'] = checkin_at_hour(
        day,
        hour)  # adds column df['checkin_at_hour'] for use in size calculation

    # checkin_vals = df['checkin_at_hour']
    sz = sizes(df['checkin_at_hour'], z)
    print(sz[:20])
    df['flag_1'] = selection_1(neighborhood.value)
    df['flag_2'] = selection_2(ambience.value)
    df['flag_3'] = selection_3(alcohol.value)
    df['flag_4'] = selection_4(category.value)
    df['flag_5'] = agg_selection(df['flag_1'], df['flag_2'], df['flag_3'],
                                 df['flag_4'])
    clr = colors(df['flag_5'])
    alp = alpha(df['flag_5'])
    output_file("gmap.html")

    map_options = GMapOptions(lat=lt, lng=lg, map_type="roadmap", zoom=z)
    bus_hover = HoverTool(tooltips=[('Business Name', '@name'),
                                    ('Reviews', '@review_count'),
                                    ('Checkins', '@checkin_at_hr')],
                          names=["bus_hover"])

    p = gmap("AIzaSyBZ66UcTIUAyZBWhrhs8JLTzth9yMorgQU",
             map_options,
             title="Vegas",
             plot_width=800,
             tools=[bus_hover, 'reset', 'pan', 'lasso_select'])

    source = ColumnDataSource(data=dict(lat=df['latitude'],
                                        lon=df['longitude'],
                                        size=sz,
                                        color=clr,
                                        alpha=alp,
                                        name=df['name'],
                                        review_count=df['review_count'],
                                        checkin_at_hr=df['checkin_at_hour']))

    p.circle(x="lon",
             y="lat",
             size="size",
             fill_alpha="alpha",
             fill_color="color",
             name="bus_hover",
             line_width=1,
             line_alpha=0,
             hover_alpha=1.0,
             source=source)

    return p
예제 #27
0
파일: app.py 프로젝트: jkattirtzi/Insight
def option():
    if request.method == 'GET':
        route_n = request.args.get('route_n', '')
        option = get_option(route_n)
        if option == "Route1":
            df = pd.read_csv("./data/df1out.csv")
            coords, lat_mean, lon_mean = get_coords(df)
        elif option == "Route2":
            df = pd.read_csv("./data/df2out.csv")
            coords, lat_mean, lon_mean = get_coords(df)
        elif option == "Route3":
            df = pd.read_csv("./data/df3out.csv")
            coords, lat_mean, lon_mean = get_coords(df)
        elif option == "Route4":
            df = pd.read_csv("./data/df4out.csv")
            coords, lat_mean, lon_mean = get_coords(df)
        elif option == "Route5":
            df = pd.read_csv("./data/df5out.csv")
            coords, lat_mean, lon_mean = get_coords(df)
        figure = make_plot(df)
        fig_script, fig_div = components(figure)

    map_options = GMapOptions(lat=lat_mean,
                              lng=lon_mean,
                              map_type="roadmap",
                              zoom=14)
    #map_options = GMapOptions(lat=51.759, lng=-1.255, map_type="roadmap", zoom=15)
    google_api = 'AIzaSyBdPAkzHMWahHjT9ml9zGeM6pR3u-VucKc'
    fig_map = gmap(google_api,
                   map_options,
                   title="Route Taken",
                   plot_height=400,
                   plot_width=500)
    fig_map.xaxis.axis_label = 'Longitude'
    fig_map.yaxis.axis_label = 'Latitude'
    source = ColumnDataSource(coords)
    fig_map.circle(x="lon",
                   y="lat",
                   size=5,
                   fill_color="blue",
                   fill_alpha=0.8,
                   source=source)
    #    show(fig_map)
    script2, div2 = components(fig_map)

    #figure = make_plot()
    #fig_script, fig_div = components(figure)
    return render_template("location2.html.j2",
                           option=option,
                           route_n=route_n,
                           fig_script=fig_script,
                           fig_div=fig_div,
                           bkversion=bokeh.__version__,
                           df=df,
                           script2=script2,
                           div2=div2)
예제 #28
0
def make_plot(store_now, store_future, ecom_zipcode_all):
    # Source: http://www.bigendiandata.com/2017-06-27-Mapping_in_Jupyter/

    from bokeh.io import output_file, output_notebook, show
    from bokeh.models import GMapOptions, ColumnDataSource, CategoricalColorMapper, HoverTool, LassoSelectTool
    from bokeh.palettes import RdBu3
    from bokeh.plotting import gmap

    map_options = GMapOptions(lat=42.37,
                              lng=-71.23,
                              map_type="roadmap",
                              zoom=10)

    plot = gmap(map_options=map_options,
                google_api_key='AIzaSyCrnuAv4K0j80AZzUsYFS2NwyY49-yMXRI',
                plot_width=780,
                plot_height=780,
                output_backend="webgl")
    plot.title.text = "PUMA Retail Store and Ecommerce Transactions"

    mapper = CategoricalColorMapper(
        factors=['Unreached', 'Reached', 'Future Reach'],
        palette=[RdBu3[1], RdBu3[0], RdBu3[2]])

    plot1 = plot.square(x="lng",
                        y="lat",
                        size=20,
                        color='blue',
                        source=store_now)
    plot2 = plot.square(x="lng",
                        y="lat",
                        size=20,
                        color='red',
                        source=store_future)
    plot3 = plot.circle(x="lng",
                        y="lat",
                        size='Size',
                        fill_color={
                            'field': 'inrange',
                            'transform': mapper
                        },
                        source=ecom_zipcode_all,
                        legend='inrange')

    tooltips1 = [("Ship To ZipCode", "@store_zip"),
                 ("Ship To City", "@in_city"),
                 ('Ecom Transactions', '@Transactions')]
    plot.add_tools(HoverTool(tooltips=tooltips1, renderers=[plot3]))

    tooltips3 = [("Store ZipCode", "@store_zip"), ("City located", "@in_city"),
                 ('Ecom Transactions in range', '@Transactions')]
    plot.add_tools(HoverTool(tooltips=tooltips3, renderers=[plot2]))

    plot.add_tools(LassoSelectTool())

    return plot
예제 #29
0
    def make_plot(self):
        hover_tool = HoverTool(tooltips=[
            ("Station", "@target_station"),
        ])

        dataframe = self.found_wsc_stations_source.data

        current_loc = self.current_location_source.data

        map_options = GMapOptions(
            lat=current_loc['lat'][0],
            lng=current_loc['lng'][0],
            map_type="hybrid",
            zoom=8
        )

        BASE_DIR = os.path.dirname(os.path.dirname(
            os.path.dirname(
                os.path.dirname(os.path.abspath(__file__)))))

        with open('dashboard/api_key/client_secret_548109306400.json') as f:
            GOOGLE_API_KEY = json.load(f)

        self.plot = gmap(google_api_key=GOOGLE_API_KEY['api_key'], name='map',
                         map_options=map_options, width=900, height=400,
                         tools=TOOLS,
                         title=TITLE)

        self.plot.circle(x="Longitude", y="Latitude", size=15,
                         fill_color="blue", fill_alpha=0.8,
                         source=self.found_wsc_stations_source,
                         # set visual properties for selected glyphs
                         selection_color="orange",
                         nonselection_fill_alpha=0.6,
                         legend="WSC Stations"
                         )

        self.plot.inverted_triangle(x="lng", y="lat", size=11,
                                    fill_color="red", fill_alpha=0.8,
                                    source=self.current_location_source,
                                    legend='Target Location')

        self.plot.on_event(DoubleTap, self.map_callback)

        return column(row(self.plot,
                          column(self.search_parameter_text,
                                 self.lat_input,
                                 self.lng_input,
                                 self.coordinate_input_warning,
                                 self.search_distance_select,
                                 )
                          ),
                      self.station_summary_text,
                      self.station_summary_table,
                      )
def plot(df, palette, filename):

    df['latitude'] = np.float64(df['latitude'])
    df['longitude'] = np.float64(df['longitude'])
    latitude_list = [x for x in df['latitude'].values]
    longitude_list = [x for x in df['longitude'].values]
    rent = ['$' + str(x) for x in df['Rent'].values]
    scale = np.array(df['Rent'].values) / max(df['Rent'].values)
    new_scale = [int(i * 10) for i in scale]
    scale_drop_duplicates = list(set(new_scale))

    radius = [x * 100 for x in new_scale]

    colors = brewer[palette][9]
    colors = colors[::-1]

    colormap = dict(zip(scale_drop_duplicates, colors))
    colors = [colormap[x] for x in new_scale]

    map_options = GMapOptions(lat=33.4484,
                              lng=-112.0740,
                              map_type="roadmap",
                              zoom=12)
    api_key = config.gmap_api_key

    source = ColumnDataSource(data=dict(lat=latitude_list,
                                        lon=longitude_list,
                                        radius=radius,
                                        colors=colors,
                                        alpha=scale,
                                        label=rent))

    hover = HoverTool(tooltips=[("Rent", "@label")])

    bokeh_plot = gmap(api_key,
                      map_options,
                      tools=[hover,
                             WheelZoomTool(),
                             PanTool(),
                             BoxZoomTool()],
                      title='Phoenix Housing Data (Rent per Sq. Ft.)')

    bokeh_plot.circle(x="lon",
                      y="lat",
                      radius="radius",
                      fill_color="colors",
                      line_color="colors",
                      line_width=2,
                      line_alpha=0.3,
                      fill_alpha=0.8,
                      source=source)
    output_file(filename)
    png_file = 'Figures/' + filename.split('.')[0] + '.png'
    export_png(bokeh_plot, filename=png_file)
    show(bokeh_plot)