Exemplo n.º 1
0
def plot_predict():
    collection = db['gps_predict']
    df = pd.DataFrame(collection.find_one({'_id': 'file'})['data'])
    data = go.Figure()
    data.add_trace(
        go.Scattermapbox(lon=df['real_lon'],
                         lat=df['real_lat'],
                         mode='lines',
                         name='original'))
    data.add_trace(
        go.Scattermapbox(lon=df['pred_lon'],
                         lat=df['pred_lat'],
                         mode='lines',
                         name='prediction'))

    c_lon = (max(df['real_lon']) + min(df['real_lon'])) / 2
    c_lat = (max(df['real_lat']) + min(df['real_lat'])) / 2

    data.update_layout(margin={
        'l': 0,
        't': 0,
        'b': 0,
        'r': 0
    },
                       mapbox={
                           'style': "stamen-terrain",
                           'zoom': 12.5,
                           'center': {
                               'lon': c_lon,
                               'lat': c_lat
                           }
                       })

    graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)
    return graphJSON
Exemplo n.º 2
0
def update_map(value, value2):
    return {
        "data": [
            go.Scattermapbox(
                            lon = [value],
                            lat = [value2],
                            text = ["Current location"],
                            mode = 'markers',
                            marker=go.scattermapbox.Marker(size=15, color = 'rgb(66, 129, 255)'),
                            name = 'Current location'
                        ),
            go.Scattermapbox(
                            lon = df.Longitude[:2000],
                            lat = df.Latitude[:2000],
                            name = 'Recorded accident',
                            text = severity_list[:2000]
                        )],
        "layout": go.Layout(
                        title = 'Accident Location',
                        width = 900,
                        height = 600,
                        mapbox = go.layout.Mapbox(
                            accesstoken = access_token,
                            center = go.layout.mapbox.Center(
                                lat = value2,
                                lon = value,
                            ),
                            style="streets",
                            zoom = 12
                        )
                    )
    }
def update_map(n, value):

    if value == None:
        data = [go.Scattermapbox(name='dataset', mode='markers')]

    else:
        data = [
            go.Scattermapbox(
                lon=all_data[value]['lon'],
                lat=all_data[value]['lat'],
                text=all_data[value]['name'] + '- População ' +
                all_data[value]['pop'].astype(str),
                mode='markers',
                marker=go.scattermapbox.Marker(
                    # size = all_data[value]['pop']/marker_scale,
                    size=15,
                    colorscale='Portland',
                    color=all_data[value]['pop'],
                    showscale=False))
        ]

    layout = go.Layout(height=840,
                       margin=dict(t=30),
                       autosize=True,
                       hovermode='closest',
                       uirevision='dataset',
                       mapbox=go.layout.Mapbox(accesstoken=mapbox_access_token,
                                               bearing=0,
                                               center=go.layout.mapbox.Center(
                                                   lat=init_lat, lon=init_lon),
                                               pitch=0,
                                               zoom=init_zoom))

    fig = go.Figure(data=data, layout=layout)
    return fig
Exemplo n.º 4
0
def matPlot(desiredData):
    df = desiredData
    data = []
    opacity_level = 0.8
    MC_conc = df['Microcystin (ug/L)']
    # make bins
    b1 = df[MC_conc <= USEPA_LIMIT]
    b2 = df[(MC_conc > USEPA_LIMIT) & (MC_conc <= WHO_LIMIT)]
    b3 = df[MC_conc > WHO_LIMIT]
    data.append(
        go.Scattermapbox(lon=b1['LONG'],
                         lat=b1['LAT'],
                         mode='markers',
                         text=b1["Body of Water Name"],
                         visible=True,
                         name="MC <= USEPA Limit",
                         marker=dict(color="green", opacity=opacity_level)))
    data.append(
        go.Scattermapbox(lon=b2['LONG'],
                         lat=b2['LAT'],
                         mode='markers',
                         text=b2["Body of Water Name"],
                         visible=True,
                         name="MC <= WHO Limit",
                         marker=dict(color="orange", opacity=opacity_level)))
    data.append(
        go.Scattermapbox(lon=b3['LONG'],
                         lat=b3['LAT'],
                         mode='markers',
                         text=b3["Body of Water Name"],
                         visible=True,
                         name="MC > WHO Limit",
                         marker=dict(color="red", opacity=opacity_level)))
    fig = dict(data=data, layout=layout)
    return fig
Exemplo n.º 5
0
def lineConnection(maxRail, returnPlotMap):
    """ A function for plotting the assigned connections between stations (line).

        Args:
            maxRail: line with maximum score (determined by an algorithm)
            returnPlotMap: RailwayList, stationList, data
    """
    stationList = returnPlotMap[1]
    alreadyListed = []

    # for all trajectories in line
    for i in range(len(maxRail.TrajectoryList)):

        # determine random color for line
        r = random.randint(0, 255)
        g = random.randint(0, 255)
        b = random.randint(0, 255)
        trajColor = 'rgb(' + str(r) + ', ' + str(g) + ', ' + str(b) + ')'

        countLegend = 0
        label = "Trajectory " + str(i+1)
        for j in range(len(maxRail.TrajectoryList[i].Raillist)):
            y1, y2, x1, x2 = connect(maxRail.TrajectoryList[i].Raillist[j].stationBeginning,
                                     maxRail.TrajectoryList[i].Raillist[j].stationEnd, stationList)
            coordinates = [y1, y2, x1, x2]

            # check if rail is used multiple times
            countEven = 1
            countOdd = 2
            count = 1
            for coordinateBlock in alreadyListed:
                if (coordinateBlock == coordinates):
                    count += 1
                    if (count % 2 == 0):
                        countEven += 1
                    else:
                        countOdd += 1

            alreadyListed.append(coordinates)
            coordinatesReverse = [y2, y1, x2, x1]
            alreadyListed.append(coordinatesReverse)

            if (countLegend == 0):
                legendShow = True
            else:
                legendShow = False

            # if count even, scattermapbox query for plotting rail, extra curve
            if (count % 2 == 0):
                result = gob.Scattermapbox(lat=[y1, (y1+y2-0.001*countEven)/2, y2], lon=[x1, (x1+x2-0.001*countEven)/2, x2], mode='lines',
                                           line=dict(width=2, color=trajColor), name=label, legendgroup=label, showlegend=legendShow)

           # if count odd, scattermapbox query for plotting, extra curve other side
            else:
                result = gob.Scattermapbox(lat=[y1, (y1+y2+0.001*countOdd)/2, y2], lon=[x1, (x1+x2+0.001*countOdd)/2, x2], mode='lines',
                                           line=dict(width=2, color=trajColor), name=label, legendgroup=label, showlegend=legendShow)

           # put query in list for later use
            dataVisualise.append(result)
            countLegend += 1
Exemplo n.º 6
0
def plot_sim(obj, decoded):
    line_points_index = obj.index
    line_points = obj.line_points[line_points_index - 1:]
    lati = [i[0] for i in line_points]
    long = [i[1] for i in line_points]
    lati_sd = [i[0] for i in decoded]
    long_sd = [i[1] for i in decoded]
    fig = go.Figure(go.Scattermapbox(lat=lati, lon=long, mode='lines'))

    pos = obj.move()
    fig.add_trace(
        go.Scattermapbox(
            lat=[pos[0]],
            lon=[pos[1]],
            mode='markers',
            marker=go.scattermapbox.Marker(size=20, symbol="car"),
        ))

    fig.add_trace(go.Scattermapbox(lat=lati_sd, lon=long_sd, mode='lines'))

    fig.update_layout(
        autosize=True,
        hovermode=False,
        mapbox=go.layout.Mapbox(accesstoken=mapbox_access_token,
                                bearing=0,
                                center=go.layout.mapbox.Center(
                                    lat=obj.car_pos[0], lon=obj.car_pos[1]),
                                pitch=0,
                                zoom=15),
    )
    # fig.show()
    return json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
Exemplo n.º 7
0
def mapConnection(returnPlotMap):
    """ A function for plotting all railways between stations.

        Args:
            returnPlotMap: RailwayList, stationList, data
    """
    RailwayList = returnPlotMap[0]
    stationList = returnPlotMap[1]
    countLegend = 0

    # for all possible connections in the map, determine coordinates
    for connection in RailwayList:
        y1, y2, x1, x2 = connect(connection.stationBeginning, connection.stationEnd, stationList)

        # scattermapbox query for plotting connections, all in 1 legendgroup
        if (countLegend == 0):
            result = gob.Scattermapbox(lat=[y1, y2], lon=[x1, x2], mode='lines', line=dict(width=1, color='grey'),
                                       name='All rails', legendgroup='All rails')
        # only a legend for the first (no duplicates)
        else:
            result = gob.Scattermapbox(lat=[y1, y2], lon=[x1, x2], mode='lines', line=dict(width=1, color='grey'),
                                       name='All rails', legendgroup='All rails', showlegend=False)
        countLegend += 1

        # all queries in a list for later use
        dataVisualise.append(result)
Exemplo n.º 8
0
def update_map(region, color_var, size_var):
    print(region, color_var, size_var)

    if region:
        trd_selection = trd[trd.CONJ.isin(region)]

        color_norm = trd_selection[color_var].clip(
            0, trd_selection[color_var].quantile(0.9))

        if size_var == 'FIX_SIZE':
            size_norm = 10
        else:
            trd_max = trd_selection[size_var].quantile(0.95)
            size_norm = np.log1p(trd_selection[size_var] / trd_max) * 30
            size_norm.clip(5, 25, inplace=True)

        map_data = [
            go.Scattermapbox(
                lat=trd_selection.lat,
                lon=trd_selection.lon,
                mode='markers',
                marker=dict(size=size_norm,
                            color=color_norm,
                            colorscale='RdBu',
                            showscale=True),
            )
        ]
    else:
        map_data = [go.Scattermapbox(lat=[], lon=[], mode='markers')]

    return dict(data=map_data, layout=map_layout)
Exemplo n.º 9
0
def build_set(rating, ms):
    if rating == 'selected':
        run, col = ms[0]

        return go.Scattermapbox(
            name='selected',
            lat=[run.put_in_latitude],
            lon=[run.put_in_longitude],
            text=[
                f'{run.run_name}</br></br>rating: {run.class_rating}</br>distance: {run.distance} mile(s)'
            ],
            ids=[run.run_id],
            mode='markers',
            marker=dict(size=24, color='#AEFF0D', opacity=0.8,
                        symbol='circle'),
            showlegend=False,
            hoverinfo='text')
    else:
        return go.Scattermapbox(
            name=rating,
            lat=[run.put_in_latitude for run in ms],
            lon=[run.put_in_longitude for run in ms],
            text=[
                f'{run.run_name}</br></br>rating: {run.class_rating}</br>distance: {run.distance} mile(s)'
                for run in ms
            ],
            ids=[run.run_id for run in ms],
            mode='markers',
            marker=dict(
                size=12,
                color=COLOR_MAP[rating],
                opacity=0.8,
            ),
            hoverinfo='text')
Exemplo n.º 10
0
def draw_city_map(lat, lon, streets, streets_locations_number, city_center,
                  zoom):
    style = styles.CityMapStyle

    marker_sizes = [
        x if x < style.MAX_MARKER_SIZE else style.MAX_MARKER_SIZE
        for x in streets_locations_number
    ]
    marker_sizes = [
        x if x > style.MIN_MARKER_SIZE else style.MIN_MARKER_SIZE
        for x in marker_sizes
    ]

    round3 = lambda x: round(float(x), 3)

    hover_template = "<i>{}</i><br>coords: {:.3f} {:.3f}<br>n_locations: {}"
    hover_func = lambda x, y, z, zz: hover_template.format(
        x, round3(y), round3(z), zz)
    scatter_hover = list(
        map(hover_func, streets, lat, lon, streets_locations_number))

    marker_labels = [
        str(x) if x >= style.MIN_LABELED_SIZE else ""
        for x in streets_locations_number
    ]

    data = [
        go.Scattermapbox(lat=lat,
                         lon=lon,
                         mode='markers',
                         marker=dict(size=marker_sizes,
                                     color=style.MARKER_COLOR,
                                     opacity=style.MARKER_OPACITY),
                         text=scatter_hover,
                         hoverinfo='text'),
        go.Scattermapbox(lat=lat,
                         lon=lon,
                         mode='text',
                         marker=dict(size=marker_sizes,
                                     color=style.MARKER_COLOR,
                                     opacity=style.MARKER_OPACITY),
                         text=marker_labels,
                         textfont=dict(color='darkred', family='arial'),
                         hoverinfo='none')
    ]

    layout = go.Layout(width=style.MAP_WIDTH,
                       height=style.MAP_HEIGHT,
                       hovermode='closest',
                       margin=style.MARGIN,
                       showlegend=False,
                       mapbox=dict(accesstoken=consts.MAPBOX_TOKEN,
                                   center=dict(lat=city_center[0],
                                               lon=city_center[1]),
                                   zoom=zoom,
                                   style='light'))

    fig = dict(data=data, layout=layout)
    py.iplot(fig, show_link=False)
def update_map(county, subcounty):
    zoom = 5.0
    lat_initial = -1.2921
    long_initial = 36.8219
    bearing = 0

    # Also add for only county selection
    if county and subcounty:
        zoom = 5.0
        lat_initial = counties_constituencies_coords[county][subcounty]["Lat"]
        long_initial = counties_constituencies_coords[county][subcounty][
            "Long"]
    scale = 100

    return go.Figure(
        data=[
            # Data for all regions
            go.Scattermapbox(
                lat=confirmed_global["Lat"],
                lon=confirmed_global["Long"],
                mode="markers",
                hoverinfo="lat+lon+text",
                text=with_text['Text'],
                marker=go.scattermapbox.Marker(
                    showscale=False,
                    color='red',
                    opacity=0.9,
                    size=8,
                ),
            ),
            # Have here plot of kenya on the map
            go.Scattermapbox(
                lat=kenya_data['Lat'],
                lon=kenya_data['Long'],
                mode='markers',
                hoverinfo='text',
                text=kenya_data['County'] + ": " +
                kenya_data[ke_date].astype(str),
                marker=go.scattermapbox.Marker(
                    showscale=False,
                    color='red',
                    opacity=1.0,
                    size=10,
                ),
            ),
        ],
        layout=go.Layout(
            autosize=True,
            margin=go.layout.Margin(l=0, r=20, t=0, b=0),
            showlegend=False,
            mapbox=dict(
                accesstoken=mapbox_access_token,
                center=dict(lat=lat_initial, lon=long_initial),
                style="dark",
                bearing=bearing,
                zoom=zoom,
            ),
        ),
    )
Exemplo n.º 12
0
def _update_graph(map_style, region):
    dff = dataframe
    radius_multiplier = {'inner': 1.5, 'outer': 3}

    layout = go.Layout(
        title=metadata['title'],
        autosize=True,
        hovermode='closest',
        height=750,
        font=dict(family=theme['font-family']),
        margin=go.Margin(l=0, r=0, t=45, b=10),
        mapbox=dict(
            accesstoken=mapbox_access_token,
            bearing=0,
            center=dict(
                lat=regions[region]['lat'],
                lon=regions[region]['lon'],
            ),
            pitch=0,
            zoom=regions[region]['zoom'],
            style=map_style,
        ),
    )

    data = go.Data([
        # outer circles represent magnitude
        go.Scattermapbox(
            lat=dff['Latitude'],
            lon=dff['Longitude'],
            mode='markers',
            marker=go.Marker(
                size=dff['Magnitude'] * radius_multiplier['outer'],
                colorscale=colorscale_magnitude,
                color=dff['Magnitude'],
                opacity=1,
            ),
            text=dff['Text'],
            # hoverinfo='text',
            showlegend=False,
        ),
        # inner circles represent depth
        go.Scattermapbox(
            lat=dff['Latitude'],
            lon=dff['Longitude'],
            mode='markers',
            marker=go.Marker(
                size=dff['Magnitude'] * radius_multiplier['inner'],
                colorscale=colorscale_depth,
                color=dff['Depth'],
                opacity=1,
            ),
            # hovering behavior is already handled by outer circles
            hoverinfo='skip',
            showlegend=False
        ),
    ])

    figure = go.Figure(data=data, layout=layout)
    return figure
Exemplo n.º 13
0
def plot_nearby_for_site(site_object):
    nearby_lat = []
    nearby_lng = []
    nearby_name = []
    site_lat = []
    site_lng = []

    nearby_places = get_nearby_places_for_site(site_object)

    query = site_object.name + ' ' + site_object.type + ' ' + site_object.address_street
    queryurl = "https://maps.googleapis.com/maps/api/place/textsearch/json"
    param = {'query': query, 'key': google_places_key}
    page_text = make_request_using_cache(queryurl, param)
    page_text = json.loads(page_text)
    result = page_text['results']
    if result:
        location = result[0]['geometry']['location']
        if location['lat']:
            site_lat.append(location['lat'])
            site_lng.append(location['lng'])
        else:
            return

    for each in nearby_places:
        nearby_name.append(each.name)
        nearby_lat.append(each.lat)
        nearby_lng.append(each.lng)

    data = [
        go.Scattermapbox(
            lat=nearby_lat,
            lon=nearby_lng,
            mode='markers',
            marker=go.scattermapbox.Marker(size=7),
            text=nearby_name,
        ),
        go.Scattermapbox(
            lat=site_lat,
            lon=site_lng,
            mode='markers',
            marker=go.scattermapbox.Marker(size=10, symbol='star'),
            text=site_object.name,
        )
    ]

    layout = go.Layout(
        autosize=True,
        hovermode='closest',
        mapbox=go.layout.Mapbox(accesstoken=mapbox_access_token,
                                bearing=0,
                                center=go.layout.mapbox.Center(
                                    lat=site_lat[0], lon=site_lng[0]),
                                pitch=0,
                                zoom=10),
    )

    fig = go.Figure(data=data, layout=layout)
    fig.show()
Exemplo n.º 14
0
def geo_plot_html(activity, intervals, map_interval_type):
    filtered_intervals = intervals[intervals.type == map_interval_type].filter(
        ["start", "stop", "color", "name"])

    # TODO Find way to always give a correct zoom
    # long_diff = max(filter_act.longitude) - min(filter_act.longitude)
    # lat_diff = max(filter_act.latitude) - min(filter_act.latitude)
    # biggest_diff = max(long_diff, lat_diff)
    #
    # diff = np.arange(0.016, 0.8, 0.01).tolist()
    # zoom_values = np.linspace(12.5, 9, num=len(diff))
    # index = min(enumerate(diff), key=lambda x: abs(x[1] - biggest_diff))
    # print("lat/long diff: " + str(biggest_diff) + "zoom: " + str(zoom_values[index[0]]))
    fig = go.Figure(
        go.Scattermapbox(lat=activity.latitude,
                         lon=activity.longitude,
                         hoverinfo="skip",
                         name="Entire Ride"))

    for index, row in filtered_intervals.iterrows():
        interval = activity[(activity.seconds >= row.start)
                            & (activity.seconds < row.stop)]
        hovertext = []
        for i, value in interval.iterrows():
            hovertext.append(row["name"] + "<br>" +
                             str(round(value.distance, 2)) + "Km")

        fig.add_trace(
            go.Scattermapbox(lon=interval.longitude,
                             lat=interval.latitude,
                             marker={
                                 'size': 10,
                                 'symbol': "circle"
                             },
                             hoverinfo="text",
                             hovertext=hovertext,
                             visible="legendonly",
                             name=row["name"]))

    fig.update(layout=dict(
        paper_bgcolor=gc_bg_color,
        plot_bgcolor=gc_bg_color,
        mapbox_style="open-street-map",
        mapbox=dict(
            center=dict(
                lat=activity.latitude.mean(),
                lon=activity.longitude.mean(),
            ),
            zoom=9,
        ),
        margin=go.layout.Margin(l=0, r=0, b=0, t=25, pad=0),
        legend=go.layout.Legend(
            traceorder="normal",
            font=dict(color=gc_text_color, ),
        ),
    ), )
    # fig.update_layout(legend_orientation="h")
    return plotly.offline.plot(fig, output_type='div', auto_open=False)
Exemplo n.º 15
0
def generateMap(stationInfo, typeList, selected):
    lat0 = (max(stationInfo['lat']) + min(stationInfo['lat'])) / 2
    lon0 = (max(stationInfo['lon']) + min(stationInfo['lon'])) / 2

    traces = []
    alldata = []

    for Type in selected:
        trace = go.Scattermapbox(
            lat=stationInfo['lat'][typeList[Type]],
            lon=stationInfo['lon'][typeList[Type]],
            mode="markers",
            name=nameSet[Type],
            marker=dict(
                size=20,
                color=colorSet[Type],
            ),
            hovertext=stationInfo['name'][typeList[Type]],
            hoverinfo="text",
        )
        traces.append(trace)
        alldata.extend(typeList[Type])

    tracebg = go.Scattermapbox(
        lat=stationInfo['lat'][alldata],
        lon=stationInfo['lon'][alldata],
        mode="markers",
        marker=dict(
            size=25,
            color='black',
        ),
        hoverinfo="none",
        showlegend=False,
    )

    layout = go.Layout(
        mapbox_style="open-street-map",
        margin={
            "r": 0,
            "t": 0,
            "l": 0,
            "b": 0
        },
        mapbox=dict(zoom=5,
                    center=dict(lat=lat0, lon=lon0),
                    pitch=0,
                    style='light'),
        legend=dict(
            bgcolor="#1f2c56",
            orientation="v",
            font=dict(color="white"),
            x=0,
            y=0,
            yanchor="bottom",
        ),
    )
    return go.Figure(data=[tracebg, *traces], layout=layout)
Exemplo n.º 16
0
def render_map(map_style='satellite-streets'):
    token = 'pk.eyJ1IjoiZG91Z2ZpbmNoIiwiYSI6ImNqZHhjYnpqeDBteDAyd3FsZXM4ZGdqdTAifQ.xLS22vmqzVYR0SAEDWdLpQ'

    plume_lons, plume_lats = load_plume_data()
    ps_lons, ps_lats = load_ps_data()
    flare_lons, flare_lats = load_flare_data()

    fig = go.Figure()

    fig.add_trace(
        go.Scattermapbox(mode="markers",
                         name='Power Stations',
                         lon=ps_lons,
                         lat=ps_lats,
                         hoverinfo='none',
                         marker={
                             'color': 'red',
                             'opacity': 0.8,
                             'size': 5
                         }))

    fig.add_trace(
        go.Scattermapbox(mode="lines",
                         fill="toself",
                         name='Nighttime Flaring',
                         lon=flare_lons,
                         lat=flare_lats,
                         hoverinfo='none',
                         marker={'color': '#e07509'}))

    fig.add_trace(
        go.Scattermapbox(mode="lines",
                         fill="toself",
                         name='NO<sub>2</sub> Plumes',
                         lon=plume_lons,
                         lat=plume_lats,
                         hoverinfo='none',
                         marker={'color': '#006391'}))

    fig.update_layout(mapbox={
        'style': "stamen-terrain",
        'center': {
            'lon': 0,
            'lat': 30
        },
        'zoom': 2
    })
    fig.update_layout(mapbox_style=map_style, mapbox_accesstoken=token)
    fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}, autosize=True)
    fig.update_layout(legend=dict(title='Click to show/hide',
                                  yanchor="top",
                                  y=0.99,
                                  xanchor="left",
                                  x=0.01))

    return fig
Exemplo n.º 17
0
def example_multi():
    """https://community.plot.ly/t/take-a-single-df-and-break-it-into-two-scattermapbox-traces-using-list-comprehension/17763/8"""
    from plotly.offline import init_notebook_mode, iplot
    import plotly.graph_objs as go
    init_notebook_mode()

    mapbox_access_token = '...'

    data = [
        go.Scattermapbox(lat=['45.5017'],
                         lon=['-73.5673'],
                         mode='markers',
                         marker=dict(size=14),
                         name='mapbox 1',
                         text=['Montreal'],
                         subplot='mapbox'),
        go.Scattermapbox(lat=['45.7'],
                         lon=['-73.7'],
                         mode='markers',
                         marker=dict(size=14),
                         name='mapbox 1',
                         text=['Montreal 2'],
                         subplot='mapbox'),
        go.Scatter(y=[1, 3, 2], xaxis='x', yaxis='y', name='scatter 1'),
        go.Scatter(y=[3, 2, 1], xaxis='x', yaxis='y', name='scatter 2'),
        go.Bar(y=[1, 2, 3], xaxis='x2', yaxis='y2', name='scatter 3'),
        go.Scatter(y=[3, 2, 1], xaxis='x2', yaxis='y2', name='scatter 4'),
    ]

    layout = go.Layout(autosize=True,
                       hovermode='closest',
                       mapbox=dict(accesstoken=mapbox_access_token,
                                   bearing=0,
                                   center=dict(lat=45, lon=-73),
                                   pitch=0,
                                   zoom=5,
                                   domain={
                                       'x': [0.3, 0.6],
                                       'y': [0.7, 1.0]
                                   }),
                       xaxis={'domain': [0.3, 0.6]},
                       yaxis={'domain': [0.36, 0.6]},
                       xaxis2={
                           'domain': [0.3, 0.6],
                           'side': 'bottom',
                           'anchor': 'y2'
                       },
                       yaxis2={
                           'domain': [0, 0.3],
                           'anchor': 'x2'
                       },
                       height=700,
                       width=700)

    fig = go.Figure(data=data, layout=layout)
    iplot(fig)
Exemplo n.º 18
0
def main():
    act = GC.activity()
    activity = pd.DataFrame(act, index=act['seconds'])
    activity = remove_incorrect_lat_long_values(activity)

    all_intervals = pd.DataFrame(GC.activityIntervals())
    filtered_intervals = all_intervals[all_intervals.type ==
                                       map_interval_type].filter(
                                           ["start", "stop", "color", "name"])

    # TODO Find way to always give a correct zoom
    # long_diff = max(filter_act.longitude) - min(filter_act.longitude)
    # lat_diff = max(filter_act.latitude) - min(filter_act.latitude)
    # biggest_diff = max(long_diff, lat_diff)
    #
    # diff = np.arange(0.016, 0.8, 0.01).tolist()
    # zoom_values = np.linspace(12.5, 9, num=len(diff))
    # index = min(enumerate(diff), key=lambda x: abs(x[1] - biggest_diff))
    # print("lat/long diff: " + str(biggest_diff) + "zoom: " + str(zoom_values[index[0]]))
    fig = go.Figure(
        go.Scattermapbox(lat=activity.latitude,
                         lon=activity.longitude,
                         hoverinfo="skip",
                         name="Entire Ride"))

    fig.update(layout=dict(mapbox_style="open-street-map",
                           margin=go.layout.Margin(l=0, r=0, b=0, t=25, pad=0),
                           mapbox=dict(
                               center=dict(
                                   lat=activity.latitude.mean(),
                                   lon=activity.longitude.mean(),
                               ),
                               zoom=9,
                           )))

    for index, row in filtered_intervals.iterrows():
        interval = activity[(activity.seconds >= row.start)
                            & (activity.seconds < row.stop)]
        hovertext = []
        for i, value in interval.iterrows():
            hovertext.append(row["name"] + "<br>" +
                             str(round(value.distance, 2)) + "Km")

        fig.add_trace(
            go.Scattermapbox(lon=interval.longitude,
                             lat=interval.latitude,
                             marker={
                                 'size': 10,
                                 'symbol': "circle"
                             },
                             hoverinfo="text",
                             hovertext=hovertext,
                             name=row["name"]))

    plotly.offline.plot(fig, auto_open=False, filename=temp_file.name)
    GC.webpage(pathlib.Path(temp_file.name).as_uri())
Exemplo n.º 19
0
    def plot_path(self, lat_list, long_list, src_lat_long,
                  destination_lat_long):
        #Given a list of latitudes and longitudes, origin and destination latitude and longitude, plots a path on a map

        # adding the lines joining the nodes
        fig = go.Figure(
            go.Scattermapbox(name="Path",
                             mode="lines",
                             lon=long_list,
                             lat=lat_list,
                             marker={'size': 10},
                             line=dict(width=4.5, color='blue')))
        # adding source marker
        fig.add_trace(
            go.Scattermapbox(name="Source",
                             mode="markers",
                             lon=[src_lat_long[1]],
                             lat=[src_lat_long[0]],
                             marker={
                                 'size': 12,
                                 'color': "red"
                             }))

        # adding destination marker
        fig.add_trace(
            go.Scattermapbox(name="Destination",
                             mode="markers",
                             lon=[destination_lat_long[1]],
                             lat=[destination_lat_long[0]],
                             marker={
                                 'size': 12,
                                 'color': 'green'
                             }))

        # getting center for plots:
        lat_center = np.mean(lat_list)
        long_center = np.mean(long_list)
        # defining the layout using mapbox_style
        fig.update_layout(mapbox_style="stamen-terrain",
                          mapbox_center_lat=30,
                          mapbox_center_lon=-80)
        fig.update_layout(margin={
            "r": 0,
            "t": 0,
            "l": 0,
            "b": 0
        },
                          mapbox={
                              'center': {
                                  'lat': lat_center,
                                  'lon': long_center
                              },
                              'zoom': 13
                          })
        fig.show()
Exemplo n.º 20
0
def map_plot(df, chemicals):
    chemicals_drop = [
        "Азот нитритный",
        "Азот аммонийный",
        "Азот нитратный",
        "Фенол",
        "Нефтепродукты",
        "Органические вещества (по ХПК)",
        "Железо",
        "Медь",
        "Цинк",
        "Марганец",
        "БПК5"
    ]
    fig = go.Figure()
    for river in rivers:
        hover = []
        if chemicals == []:
            for chem in chemicals_drop:
                val = df[df["Наименование водного объекта"]==river][chem].to_list()
                hover.append(f"{chem}: {val}")
                hovertemplate="<br>".join(hover)
            fig.add_trace(go.Scattermapbox(
                lat=[location_dic[river][0]],
                lon=[location_dic[river][1]],
                mode='markers',
                marker=dict(size=df[df["Наименование водного объекта"]==river][chemicals_drop].sum(axis=1)*10, color=location_dic[river][2]),
                textfont=dict(size=16, color='black'),
                name=river,
                hovertext=hovertemplate,
            ))
        else:
            for chem in chemicals:
                val = df[df["Наименование водного объекта"]==river][chem].to_list()
                hover.append(f"{chem}: {val}")
                hovertemplate="<br>".join(hover)
            fig.add_trace(go.Scattermapbox(
                lat=[location_dic[river][0]],
                lon=[location_dic[river][1]],
                mode='markers',
                marker=dict(size=df[df["Наименование водного объекта"]==river][chemicals].sum(axis=1)*10, color=location_dic[river][2]),
                textfont=dict(size=16, color='black'),
                name=river,
                hovertext=hovertemplate,
            ))
    fig.update_layout(mapbox_style="open-street-map")
    fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
    fig.update_layout(
        mapbox=dict(
            center=go.layout.mapbox.Center(lat=56.6, lon=68),
            zoom=6
        )
    )
    return fig
Exemplo n.º 21
0
def create_chart_mapbox(adQuery=None):

    if adQuery is None:
        return {
            'data': [
                go.Scattermapbox(
                    lat=[],
                    lon=[],
                    mode='markers',
                    marker=go.scattermapbox.Marker(size=9),
                    text=[],
                    hoverinfo='text',
                    visible=False,
                )
            ],
            'layout':
            go.Layout(
                mapbox=go.layout.Mapbox(
                    accesstoken=mapbox_access_token,
                    style='mapbox://styles/thomasvro/cjuv6sffh09s01foj7rn28quj',
                    zoom=7,
                    center=go.layout.mapbox.Center(lat=51.0, lon=4.7),
                ),
                margin=go.layout.Margin(l=120, r=120, b=0, t=80, pad=0),
            )
        }
    else:
        lat = adQuery.get('latitudes')
        lon = adQuery.get('longitudes')
        names = adQuery.get('Denomination')
        return {
            'data': [
                go.Scattermapbox(
                    lat=lat,
                    lon=lon,
                    mode='markers',
                    marker=go.scattermapbox.Marker(size=9),
                    text=names,
                    hoverinfo='text',
                )
            ],
            'layout':
            go.Layout(
                title='Entities location - based on ' + str(adQuery.count()) +
                ' entities',
                mapbox=go.layout.Mapbox(
                    accesstoken=mapbox_access_token,
                    style='mapbox://styles/thomasvro/cjuv6sffh09s01foj7rn28quj',
                    zoom=7,
                    center=go.layout.mapbox.Center(lat=51.0, lon=4.7),
                ),
                margin=go.layout.Margin(l=120, r=120, b=0, t=80, pad=0),
            )
        }
Exemplo n.º 22
0
def update_dt(rows, selected_row_indices, value):
    global sites
    global data
    global distances
    distances = []
    grocery_list = [rows[id]['Items'] for id in selected_row_indices]
    lat, lon = value.split(',')
    lat = float(lat)
    lon = float(lon)
    sites = ut.get_sites(lat, lon, grocery_list)
    lat_list = []
    lon_list = []
    for key, value in sites.items():
        #print(value)
        lat_list.append(value[0])
        lon_list.append(value[1])
        distances.append(ut.distanceCalculator(lat, lon, value[0], value[1]))
    if len(lat_list) > 0:
        data = [
            go.Scattermapbox(
                lat = lat_list,
                lon = lon_list,
                mode = 'markers',
                marker = dict(
                    size = 10,
                    color = 'rgb(200, 0, 0)'
                ),
            ),
            go.Scattermapbox(
                lat = [lat],
                lon = [lon],
                mode = 'markers',
                marker = dict(
                    size = 10
                ),
                text = ['Your location'],
            )
        ]
    else:
        data = [
            go.Scattermapbox(
                lat = [lat],
                lon = [lon],
                mode = 'markers',
                marker = dict(
                    size = 10
                ),
                text = ['Your location'],
            )
        ]
    return dict(data = data, layout = layout)
Exemplo n.º 23
0
def plot_cars(source, cars, route):
    global mapbox_access_token
    lats = [i[0] for i in cars]
    longs = [i[1] for i in cars]
    ids = [i[2] for i in cars]
    route_lats = [i[0] for i in route]
    route_longs = [i[1] for i in route]

    print("Number of Lats: ", len(lats))
    trace1 = go.Scattermapbox(lat=lats,
                              lon=longs,
                              marker={
                                  'size': 18,
                                  'symbol': ["car" for i in range(len(lats))]
                              },
                              hovertext=ids,
                              hoverinfo="text")
    trace2 = go.Scattermapbox(lat=[source.latitude],
                              lon=[source.longitude],
                              mode="markers+text",
                              marker={
                                  'size': 18,
                                  'symbol': ["star"],
                                  'color': 'rgba(255, 0, 0, 1)'
                              },
                              hovertext=['Your Location'],
                              hoverinfo="text")
    trace3 = go.Scattermapbox(lat=route_lats,
                              lon=route_longs,
                              mode='lines',
                              line={
                                  'width': 3,
                                  'color': 'rgba(0, 0, 255, 1)'
                              })

    data = [trace1, trace2, trace3]
    layout = go.Layout(autosize=True,
                       showlegend=False,
                       hovermode='closest',
                       mapbox=go.layout.Mapbox(style="outdoors",
                                               accesstoken=mapbox_access_token,
                                               bearing=0,
                                               center=go.layout.mapbox.Center(
                                                   lat=source.latitude,
                                                   lon=source.longitude),
                                               pitch=0,
                                               zoom=15))

    fig = go.Figure(data=data, layout=layout)
    fig = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
    return fig
Exemplo n.º 24
0
def update_map(region):
    print(region)

    if region:
        print(region)
        map_data = [
            go.Scattermapbox(lat=trd[trd.CONJ.isin(region)].lat,
                             lon=trd[trd.CONJ.isin(region)].lon,
                             mode='markers')
        ]
    else:
        map_data = [go.Scattermapbox(lat=[], lon=[], mode='markers')]

    return dict(data=map_data, layout=map_layout)
Exemplo n.º 25
0
def update_map(harita):

    data = []

    if "Vaka" in harita:
        map_confirmed = go.Scattermapbox(
            customdata=df_location.loc[:,
                                       ["confirmed", "deaths", "recovered"]],
            lat=df_location["lat"],
            lon=df_location["lon"],
            text=df_location["country"],
            hovertemplate="<b>%{text}<b><br><br>" +
            "Vaka Sayısı : %{customdata[0]}<br>" + "<extra></extra>",
            mode="markers",
            showlegend=True,
            marker=go.scattermapbox.Marker(size=df_location["confirmed_size"],
                                           color="green",
                                           opacity=0.7),
            name="vaka")
        data.append(map_confirmed)

    if "Ölüm" in harita:
        map_deaths = go.Scattermapbox(
            customdata=df_location.loc[:,
                                       ["confirmed", "deaths", "recovered"]],
            lat=df_location["lat"],
            lon=df_location["lon"],
            text=df_location["country"],
            hovertemplate="<b>%{text}<b><br><br>" +
            "Ölüm Sayısı : %{customdata[1]}<br>" + "<extra></extra>",
            mode="markers",
            showlegend=True,
            marker=go.scattermapbox.Marker(size=df_location["deaths_size"],
                                           color="red",
                                           opacity=0.7),
            name="ölüm")

        data.append(map_deaths)

    fig = go.Figure(data=data)
    fig.update_layout(mapbox=dict(accesstoken=mapbox_access_token,
                                  bearing=0,
                                  center=go.layout.mapbox.Center(),
                                  pitch=0,
                                  zoom=1),
                      width=1500,
                      height=800)

    return fig
Exemplo n.º 26
0
def get_map_figure(active_row=None, active_column=None):
    center = {"lat": 48.85, "lon": 2.35}
    print(center)
    state_data = [
        go.Scattermapbox(
            lat=places["lat"],
            lon=places["lon"],
            customdata=places[["name", "lat", "lon"]],
            hovertemplate="<i>%{customdata[0]}</i>" + "<br>Lon: %{customdata[1]}" + "<br>Lat: %{customdata[2]}",
            mode="markers",
            marker=dict(size=np.maximum(10, (places["total"] / 100)), color="yellow", opacity=0.2),
        )
    ]
    if active_row is not None:
        colors = {"trip_place_0": "green", "trip_place_1": "blue", "trip_place_2": "red"}
        opacities = {"trip_place_0": 0.5, "trip_place_1": 0.5, "trip_place_2": 0.5}
        opacities[active_column] = 0.9
        center_lat = (trips.loc[active_row, "coords_place_0_lat"] + trips.loc[active_row, "coords_place_2_lat"]) / 2.0
        center_lon = (trips.loc[active_row, "coords_place_0_lon"] + trips.loc[active_row, "coords_place_2_lon"]) / 2.0
        center = {"lat": center_lat, "lon": center_lon}
        for place_index in [0, 1, 2]:
            state_data.append(
                go.Scattermapbox(
                    lat=[trips.loc[active_row, "coords_place_%d_lat" % place_index]],
                    lon=[trips.loc[active_row, "coords_place_%d_lon" % place_index]],
                    mode="markers",
                    customdata=trips.loc[
                        [active_row],
                        [
                            "trip_place_%d" % place_index,
                            "coords_place_%d_lon" % place_index,
                            "coords_place_%d_lat" % place_index,
                        ],
                    ],
                    hovertemplate="<i>%{customdata[0]}</i>" + "<br>Lon: %{customdata[1]}" + "<br>Lat: %{customdata[2]}",
                    marker=dict(
                        size=20,
                        color=colors["trip_place_%d" % place_index],
                        opacity=opacities["trip_place_%d" % place_index],
                    ),
                )
            )
    print(center)
    layout = dict(
        mapbox=dict(style="open-street-map", zoom=5, center=center),
        # uirevision="no reset of zoom",
        margin=dict(r=0, l=0, t=0, b=0),
    )
    return {"data": state_data, "layout": layout}
Exemplo n.º 27
0
def make_geo_mapbox(df, chart_title, lonname, latname, textname, user_lon, user_lat):
    fig = go.Figure()
    # add database points
    fig.add_trace(
        go.Scattermapbox(
               lon = df[lonname],
               lat = df[latname],
               text = df[textname],
               name = '',
               showlegend = False,
               mode='markers',
               marker = go.scattermapbox.Marker(
                   color = df[textname],
                   size = 12,
                   showscale = True,
                   #colorscale = 'Parula',
                   autocolorscale = False,
                   symbol = 'circle',
                   colorbar_title = ''
                )
        )
    )
        # add user point
    fig.add_trace(
        go.Scattermapbox(
               lon = [user_lon],
               lat = [user_lat],
               text = ['Input Address'],
               name = '',
               showlegend = False,
               mode='markers',
               marker = go.scattermapbox.Marker(
                        showscale = False,
                        # color is only available for circle markers
                        color = 'gold',
                        size = 13,
                        symbol = 'star',
                        colorbar_title = ''
                   )
        )
    )
    fig.update_layout(title=go.layout.Title(text=chart_title), hovermode='closest', mapbox = dict(
       accesstoken=mapbox_key,
       center = go.layout.mapbox.Center(lon = user_lon, lat = user_lat),
       zoom=7
        )
    )
    return fig
Exemplo n.º 28
0
def show_activity_by_day(day_value):
    activity_df_take = activity_df[activity_df['Fecha_Retiro'] == '{:02d}'.format(day_value) + '/01/2018']\
        .groupby('Ciclo_Estacion_Retiro').count()
    activity_df_lock = activity_df[activity_df['Fecha_Arribo'] == '{:02d}'.format(day_value) + '/01/2018']\
        .groupby('Ciclo_Estacion_Arribo').count()

    sizes_take = np.zeros(480)
    sizes_lock = np.zeros(480)

    for i in range(1, 481):
        if i in activity_df_take.index:
            sizes_take[i - 1] = activity_df_take.at[i, 'Genero_Usuario']

        if i in activity_df_lock.index:
            sizes_lock[i - 1] = activity_df_lock.at[i, 'Genero_Usuario']

    return go.Figure(
        data=[
            go.Scattermapbox(lat=network_df['lat'],
                             lon=network_df['lon'],
                             mode='markers',
                             marker=dict(size=np.ceil(sizes_take / 10.),
                                         color='#FF1A1A',
                                         opacity=0.4),
                             text=network_df['name'],
                             name='Préstamos'),
            go.Scattermapbox(lat=network_df['lat'],
                             lon=network_df['lon'],
                             mode='markers',
                             marker=dict(size=np.ceil(sizes_lock / 10.),
                                         color='#FF9D1A',
                                         opacity=0.4),
                             text=network_df['name'],
                             name='Devoluciones')
        ],
        layout=go.Layout(
            margin=dict(t=60, l=60, r=60, b=60),
            autosize=False,
            #width=1000,
            height=900,
            hovermode='closest',
            mapbox=dict(accesstoken=mapbox_access_token,
                        bearing=0,
                        center=dict(lat=19.404, lon=-99.17),
                        pitch=0,
                        zoom=12.4,
                        style='light'),
        ))
Exemplo n.º 29
0
def plot_location_map():
    return html.Div([
        dcc.Graph(
            id='location-map-plot',
            config={'displayModeBar': True},
            figure={
                'data': [
                    # This plots a larger circle marker that's dark red - make's things look more like a volcano
                    go.Scattermapbox(
                        lat=df['Latitude'],
                        lon=df['Longitude'],
                        text=df['Volcano Name'],
                        hoverinfo='text',
                        mode='markers',
                        marker=dict(
                            size=17,
                            color='rgb(255, 0, 0)',
                        ),
                    ),
                    # This plots a smaller circle marker that's light red
                    go.Scattermapbox(
                        lat=df['Latitude'],
                        lon=df['Longitude'],
                        text=df['Volcano Name'],
                        hoverinfo='text',
                        mode='markers',
                        marker=dict(
                            size=8,
                            color='rgb(242, 177, 172)',
                        ),
                    ),
                ],
                'layout':
                go.Layout(
                    autosize=True,
                    hovermode='closest',
                    height=600,
                    showlegend=False,
                    plot_bgcolor=layout['plot_bgcolor'],
                    paper_bgcolor=layout['paper_bgcolor'],
                    mapbox=dict(accesstoken=MAPBOX_API_TOKEN,
                                style="dark",
                                center=dict(lat=37.615, lon=23.335),
                                zoom=3),
                ),
            },
        )
    ])
Exemplo n.º 30
0
def map_plotter(strata):
    try:
        graphs = []
        for st in strata:
            lats, lons, last_name = clustering(strata)
            graphs.append(
                go.Scattermapbox(lat=lats,
                                 lon=lons,
                                 mode='marker',
                                 marker=go.Marker(size=6,
                                                  color='rgb(255, 0, 0)',
                                                  opacity=0.7),
                                 text=last_name,
                                 hoverinfo='text'))

        layout = go.Layout(
            height=800,
            #width=500,
            title='Volcanoes',
            autosize=True,
            hovermode='closest',
            showlegend=False,
            mapbox=dict(accesstoken=token,
                        bearing=0,
                        pitch=0,
                        zoom=1.2,
                        style='light'),
        )

        fig = {'data': graphs, 'layout': layout}
        return fig

    except Exception as e:
        with open('errors.txt', 'w') as error:
            error.write(str(e))