def update_figure(selected):
    dff = (
        df_india.groupby(["State", "Confirmed", "Recovered", "Deaths"])
        .max()
        .reset_index()
    )

    def title(text):
        if text == "Confirmed":
            return "Confirmed Cases"
        elif text == "Deaths":
            return "Deaths Cases"
        elif text == "Recovered":
            return "Recovered Cases"
        else:
            return "Recovered"

    trace = go.Choroplethmapbox(
        geojson=states,
        featureidkey="properties.State",
        locations=dff.State,
        z=dff[selected],
        colorscale=colormap,
        marker_line_width=1,
    )
    return {
        "data": [trace],
        "layout": go.Layout(
            mapbox_style="mapbox://styles/cocktailsguy/ck8edouiv02lv1io9quvrr36i",
            mapbox_accesstoken=token,
            mapbox_zoom=3.1,
            mapbox_center={"lat": 21, "lon": 78},
            margin={"r": 0, "t": 0, "l": 0, "b": 0},
        ),
    }
示例#2
0
def map_prep(geojson,
             locations,
             z,
             hovertext,
             center_lon,
             center_lat,
             zoom,
             updatetime,
             mapstyle="satellite-streets",
             title='US'):

    # prepare token for Mapbox
    token = 'pk.eyJ1IjoiY2h1emhpY29uZyIsImEiOiJjazZoMG5tajIwNmh4M21ueGN0eXdtMmx6In0.kQscrYmKzfyLhN-YgENO0Q'

    data = go.Choroplethmapbox(
        geojson=geojson,
        locations=locations,
        z=z,
        hovertext=hovertext,
        hoverinfo='text',
        colorscale='YlOrRd',
        marker_line_width=0.5,
        marker_line_color='rgb(169, 164, 159)',
        colorbar=dict(title="Cases",
                      titleside="top",
                      tickmode="array",
                      tickvals=np.arange(0, 7, 1),
                      ticktext=["1", "10", "100", "1k", '10k', '100k', '1M'],
                      ticks="outside"))

    layout = go.Layout(
        mapbox={
            'accesstoken': token,
            'center': {
                'lon': center_lon,
                'lat': center_lat
            },
            'zoom': zoom,
            'style': mapstyle
        },
        margin={
            "r": 1,
            "t": 45,
            "l": 45,
            "b": 30
        },
        title=title + ' Case HeatMap',
        plot_bgcolor='#D3D3D3',
        paper_bgcolor='#D3D3D3',
        annotations=[
            dict(x=0.55,
                 y=0.03,
                 xref='paper',
                 yref='paper',
                 text='last update on ' + str(updatetime),
                 showarrow=False)
        ],  #height = graph_height, width = graph_width 
    )

    return data, layout
def display_map(hg, data_json, plot_data_json, hydro_json):
    hydro_units = ast.literal_eval(hydro_json)
    su_ids = np.sort(hydro_units[hg]['value'])
    plot_data = pd.read_json(plot_data_json, orient='split')
    plot_data1 = plot_data[plot_data.id.isin(su_ids)]

    gjson1 = ast.literal_eval(data_json)
    gjson2 = [j for j in gjson1['features'] if j['id'] in su_ids.tolist()]
    gjson = {
        'type': 'FeatureCollection',
        'bbox': gjson1['bbox'],
        'features': gjson2
    }

    fig = go.Figure(go.Choroplethmapbox(
        geojson=gjson,
        locations=plot_data1['id'],
        colorscale=plot_data1['color'].tolist(),
        marker_opacity=0.7,
        marker_line_width=0,
        showscale=False,
        text=plot_data1['name'],
        z=plot_data1.index,
        zmin=plot_data1.index.min(),
        zmax=plot_data1.index.max(),
    ),
                    layout=map_layout)

    return fig
示例#4
0
def make_heatmap(df, fig=fig):
    # Global heat map
    countries = {}
    for country in pycountry.countries:
        countries[country.name] = country.alpha_3

    country_dict = {}

    for index, row in df.iterrows():
        country_iso3 = str(row["COUNTRY_ISO3"])
        duration = int(row["DURATION"])
        duration = duration / BYTES_TO_MB
        if country_iso3 in country_dict.keys():
            country_dict[country_iso3] = country_dict[country_iso3] + duration
        else:
            country_dict[country_iso3] = duration

    with open('heatmap/world_geojson.json') as file:
        world = json.load(file)

    fig.add_trace(
        go.Choroplethmapbox(geojson=world,
                            locations=list(country_dict.keys()),
                            z=list(country_dict.values()),
                            colorscale='Darkmint',
                            zmin=0,
                            zmax=90,
                            marker_opacity=0.7,
                            marker_line_width=0))
    fig.update_layout(mapbox_style="carto-positron", mapbox_zoom=1.5)
    fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
示例#5
0
    def MakeWildfireMap(self, state, fipsData):
        fig = go.Figure(
            go.Choroplethmapbox(
                geojson=state,
                locations=fipsData.fips,
                z=fipsData.fire_count,
                colorscale="redor",
                zmin=0,
                zmax=500,
                marker_opacity=0.7,
                marker_line_width=0,
                text=fipsData.county,
                hovertemplate="%{text}" + "<extra>%{z}</extra>",
            ))
        fig.update_layout(
            mapbox_accesstoken=
            "pk.eyJ1IjoiY3NjaHJvZWQiLCJhIjoiY2s3YjJwcWk1MDFyNzNrbnpiaGdlajltbCJ9.8jO290WpRrStFoFl6oXDdA",
            mapbox_style="mapbox://styles/cschroed/cknl0nnlf219117qmeizntn9q",
            mapbox_zoom=5.20,
            mapbox_center={
                "lat": 37.502236,
                "lon": -120.962930
            })

        fig_layout = fig["layout"]
        fig_layout["paper_bgcolor"] = "rgba(0,0,0,0)"
        fig_layout["font"]["color"] = "#fcc9a1"
        fig_layout["xaxis"]["tickfont"]["color"] = "#fcc9a1"
        fig_layout["yaxis"]["tickfont"]["color"] = "#fcc9a1"

        fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
        return fig
示例#6
0
def usa_map():
    with urlopen(
            'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json'
    ) as response:
        counties = json.load(response)

    df = getdata.usa_counties()
    df.drop([2311], inplace=True)

    fig = go.Figure(
        go.Choroplethmapbox(geojson=counties,
                            locations=df.fips,
                            z=df['cases/capita'],
                            marker_opacity=0.75,
                            marker_line_width=0,
                            colorscale=[[0, '#FFFAF4'], [.005, '#FFE4CC'],
                                        [.030, '#DC654F'], [.060, '#CA3328'],
                                        [.080, '#B80000'], [.100, '#7C100C'],
                                        [.150, '#580000'], [.175, '#300000'],
                                        [1, '#170707']]))

    fig.update_layout(mapbox_style='carto-positron',
                      paper_bgcolor='rgba(0,0,0,0)',
                      mapbox_zoom=2.75,
                      mapbox_center={
                          'lat': 37.0902,
                          'lon': -95.7129
                      },
                      margin=dict(t=0, l=0, r=0, b=0))
    plot_div = plot(fig,
                    include_plotlyjs=False,
                    output_type='div',
                    config={'displayModeBar': False})

    return plot_div
def get_map_html():
    map_plot = go.Choroplethmapbox(geojson=polygons,
                                   hovertemplate=paavo_df.text,
                                   locations=paavo_df['Postal code'],
                                   z=paavo_df['Trend near future'],
                                   colorscale="Viridis",
                                   marker_opacity=0.7,
                                   marker_line_width=0,
                                   showscale=False)
    map_layout = go.Layout(width=360,
                           height=600,
                           mapbox_style="carto-positron",
                           mapbox_zoom=4.0,
                           mapbox_center={
                               "lat": 65.361064,
                               "lon": 26.985940
                           },
                           margin={
                               "r": 0,
                               "t": 0,
                               "l": 0,
                               "b": 0
                           })
    graph = dcc.Graph(id='main_plot',
                      config={'displayModeBar': False},
                      figure={
                          'layout': map_layout,
                          'data': [map_plot]
                      },
                      className="map_main_plot")
    text_block = html.Div(children=get_side_analysis(),
                          className="side_analysis",
                          id="side_info")
    map_html = html.Div(children=[graph, text_block], id="map_html")
    return map_html
示例#8
0
def map_trace(layout):

    trace_map = []

    global mapbox_accesstoken
    global df
    global selection
    global US_data
    global pl_deep
    global app

    print(df.head())
    for attribute in selection:
        trace_map.append(
            go.Choroplethmapbox(
                geojson=US_data,
                # locations=df['PostalCode_y'].tolist(),
                locations=df['PostalCode'].tolist(),
                z=df[attribute].tolist(),
                colorscale=pl_deep,
                text=addresses,
                colorbar=dict(thickness=20, ticklen=3),
                marker_line_width=0,
                marker_opacity=0.7,
                visible=False,
                subplot='mapbox1'))

    trace_map[0]['visible'] = True
    return trace_map
def death_map():
    with urlopen(
            'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json'
    ) as response:
        counties = json.load(response)

    hovertext = covid_deaths["Admin2"] + ", " + covid_deaths["Province_State"]
    fig_death = go.Figure(
        go.Choroplethmapbox(geojson=counties,
                            locations=covid_deaths["FIPS"],
                            z=covid_deaths.iloc[:, -1],
                            colorscale='Viridis',
                            zmin=0,
                            zmax=2000,
                            marker_opacity=0.5,
                            marker_line_width=0,
                            hovertext=hovertext))
    fig_death.update_layout(mapbox_style="carto-positron",
                            mapbox_zoom=4,
                            title='Latest Map and Total Death Count by County',
                            mapbox_center={
                                "lat": 40.785794,
                                "lon": -89.20973
                            })
    return fig_death
示例#10
0
def get_Choropleth(df, geo_data, arg, marker_opacity,
                   marker_line_width, marker_line_color, fig=None):
    # get_Choropleth(df, geo_data, arg, marker_opacity = 0.4, marker_line_width = 1, marker_line_color='#6666cc')

    if fig is None:
        fig = go.Figure()

    fig.add_trace(
        go.Choroplethmapbox(
            geojson=geo_data,
            locations=df['LSOA'],
            featureidkey="properties.lsoa11cd",
            colorscale=arg['colorscale'],
            z=arg['z_vec'],
            zmin=arg['min_value'],
            zmax=arg['max_value'],
            text=arg['text_vec'],
            hoverinfo="text",
            marker_opacity=marker_opacity,
            marker_line_width=marker_line_width,
            marker_line_color=marker_line_color,
            colorbar_title=arg['title'],
            colorbar_title_side='right'
        )
    )
    return fig
示例#11
0
def choropleth(geojson, location_id, variable, label):
    
    data = go.Choroplethmapbox(
        geojson = geojson,
        locations = location_id,
        z = variable,
        text = label,
        colorscale = 'reds',
        #colorbar = {'thickness':20, 'ticklen':3},
        showscale = False,
        marker_line_width=0.5, 
        marker_opacity=0.5
        
    )
    
    layout = go.Layout(
        title_text = '',
        autosize = True,
        height = 250,
        width = 350,
        margin = {'l': 10, 'r': 0, 'b': 0, 't': 0},
        mapbox = {'center': {'lat':33.677, 'lon':65.21600},
                 'accesstoken': mapbox_token,
                 'zoom':4,
                 'style': 'light'}
    )
    
    fig = go.Figure(data=data, layout=layout)

    return fig
示例#12
0
def boundary_update(boundary, measure, diag, start, end):

    # janky method for fixing dates
    start = datetime.datetime.strptime(start, '%Y-%m-%d')
    start = datetime.datetime(start.year, start.month, start.day)
    end = datetime.datetime.strptime(end, '%Y-%m-%d')
    end = datetime.datetime(end.year, end.month, end.day)

    if measure in cancer_measures:
        # TODO add a year filter, currently using all years for measure
        df = df_cancer[df_cancer['Measure'] == measure]
        df = df[(df['Period'] >= start) & (df['Period'] <= end)]
        df = df.groupby([
            boundary_codes[boundary],
            boundary_names[boundary],
            'Measure'
        ]).agg({'Value': 'sum'}).reset_index()
        df.columns = ['Code', 'Name', 'Measure', 'Value']
    elif measure in waiting_measures:
        df = waiting_times_map(measure, boundary, test=diag, start=start, end=end)
        df = df.groupby('Code').sum().reset_index()

    map_json = views[boundary]

    fig = go.Figure(
        go.Choroplethmapbox(
            geojson=map_json,
            locations=df.Code,
            z=df.Value,
            colorscale='Viridis',
            marker_line_width=0,
            marker_opacity=0.5,
        )
    )

    # figure = px.choropleth_mapbox(
    #     df,
    #     geojson=map_json,
    #     locations='Code',
    #     color='area',
    #     mapbox_style='light',
    #     center={'lat': 53, 'lon': -1.5},
    #     zoom=5,
    #     hover_name='Name',
    #     hover_data=['area'],
    # )
    #
    # figure.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

    fig.update_layout(
        mapbox_style='light',
        mapbox_accesstoken=MAPBOX_TOKEN,
        mapbox_zoom=5,
        mapbox_center={'lat': 53, 'lon': -1.5},
        margin={"r": 0, "t": 0, "l": 0, "b": 0},
        clickmode='event+select'
    )

    return fig
示例#13
0
def update_voronoi(datePicked, selectedLocation, chosen_tech, chosen_plan):
    # Voronoi
    with open("tower_vor.json") as jsonfile:
        geojson = json.load(jsonfile)
    center = {"lat": 25.6823, "lon": -100.3030}
    voronoi_fig = go.Figure(
        go.Choroplethmapbox(
            name="",
            geojson=geojson,
            locations=voronoi_df.sitio,
            z=voronoi_df.sum_bytes,
            featureidkey="properties.tower",
            colorscale="Viridis",
            hoverinfo="location+z",
            marker_opacity=0.3,
            marker_line_color="#d8d8d8",
            marker_line_width=2,
            selected_marker_opacity=0.8,
            unselected_marker_opacity=0.3,
            colorbar=dict(
                title="Consumo<br>de Datos",
                nticks=24,
                tickfont=dict(color="#d8d8d8"),
                titlefont=dict(color="#d8d8d8"),
                thicknessmode="pixels",
            ),
        ))
    voronoi_fig.add_trace(
        go.Scattermapbox(
            lon=voronoi_df.longitud,
            lat=voronoi_df.latitud,
            mode="markers",
            marker=dict(opacity=0.5, size=10),
        ))
    voronoi_fig.update_layout(
        title_text="Mapa de radiobases por regiones",
        mapbox_style="carto-darkmatter",
        mapbox_zoom=12,
        mapbox_center=center,
        autosize=True,
        margin={
            "r": 0,
            "t": 0,
            "l": 0,
            "b": 0
        },
        uirevision="foo",
        clickmode="event+select",
        hovermode="closest",
        # colorbar={"tickfont": {"color": "white"}},
        hoverdistance=2,
        mapbox=dict(
            accesstoken=mapbox_access_token,
            bearing=0,
            pitch=40,
        ),
    )
    return voronoi_fig
示例#14
0
def info_por_municipio(municipios):
    data = []
    df = get_filtered_rows(municipios)
    data.append(
        go.Choroplethmapbox(geojson=geojson,
                            locations=df['MPIOS'],
                            z=df['DESEMPLEO'],
                            colorscale='earth',
                            text=df['NOMBRE_MPI'],
                            colorbar_title="DESEMPLEO"))
    return data
示例#15
0
def create_access_map(poi_type, metric, stratum, colorscale, figure):
    """
    TODO : write docstring
    """
    if "layout" in figure:
        lat = figure["layout"]["mapbox"]["center"][
            "lat"]  # TODO: This can probably be removed now
        lon = figure["layout"]["mapbox"]["center"]["lon"]
        zoom = figure["layout"]["mapbox"]["zoom"]
    else:
        lat = float(52.48)
        lon = float(-1.89)
        zoom = float(8.5)

    selected_data = access_map_attr.loc[
        (access_map_attr['poi_type'] == poi_type)
        & (access_map_attr['metric'] == metric)
        & (access_map_attr['stratum'] == stratum)]

    data = [
        go.Choroplethmapbox(
            geojson=oa_boundaries,
            locations=selected_data['oa_id'],
            z=selected_data['value'],
            colorscale=colorscale,
            reversescale=True,
            zmin=get_scale_extremes(selected_data['value'], metric)[0],
            zmax=get_scale_extremes(selected_data['value'], metric)[1],
            marker_opacity=0.85,
            marker_line_width=0,
            colorbar=dict(
                title=dict(text=set_metric(metric), side='right'),
                titlefont=dict(size=14),
            ),
        ),
    ]

    layout = dict(
        mapbox=dict(
            layers=[],
            accesstoken=mapbox_access_token,
            center=dict(lat=lat, lon=lon),
            zoom=zoom,
        ),
        hovermode="closest",
        margin=dict(r=0, l=0, t=0, b=0),
        dragmode="lasso",
        uirevision="The User is always right",
        plot_bgcolor="#F9F9F9",
        paper_bgcolor="#F9F9F9",
    )

    return go.Figure(data=data, layout=layout)
示例#16
0
def get_custom_map_chart(geojson, locations, z, text=None):

    figure = go.Choroplethmapbox(
        geojson=geojson,
        locations=locations,
        z=z,
        colorscale='Blues',
        text=text,
        hoverinfo="text + z",
    )

    return figure
示例#17
0
def create_population_map(pop_type, colorscale, figure):
    """
    TODO : write docstring
    """
    if "layout" in figure:
        lat = figure["layout"]["mapbox"]["center"]["lat"]
        lon = figure["layout"]["mapbox"]["center"]["lon"]
        zoom = figure["layout"]["mapbox"]["zoom"]
    else:
        lat = float(52.48)
        lon = float(-1.89)
        zoom = float(8.5)

    selected_data = population_map_attr.loc[(
        population_map_attr['population'] == pop_type)]

    zmax = float(selected_data['count'].mean() +
                 (map_outlier_bound * selected_data['count'].std()))

    data = [
        go.Choroplethmapbox(
            geojson=oa_boundaries,
            locations=selected_data['oa_id'],
            z=selected_data['count'],
            colorscale=colorscale,
            reversescale=False,
            zmin=0,
            zmax=zmax,
            marker_opacity=0.85,
            marker_line_width=0,
            colorbar=dict(
                title=dict(text='Population', side='right'),
                titlefont=dict(size=14),
            ),
        ),
    ]

    layout = dict(
        mapbox=dict(
            layers=[],
            accesstoken=mapbox_access_token,
            center=dict(lat=lat, lon=lon),
            zoom=zoom,
        ),
        hovermode="closest",
        margin=dict(r=0, l=0, t=0, b=0),
        dragmode="lasso",
        uirevision="The User is always right",
        plot_bgcolor="#F9F9F9",
        paper_bgcolor="#F9F9F9",
    )

    return go.Figure(data=data, layout=layout)
示例#18
0
def create_at_risk_map(poi_type, metric, stratum, pop_type, click,
                       access_slider, population_slider):
    """
    TODO : write docstring
    """

    selected_access_data = access_map_attr.loc[
        (access_map_attr['poi_type'] == poi_type)
        & (access_map_attr['metric'] == metric)
        & (access_map_attr['stratum'] == stratum)]

    selected_pop_data = population_map_attr.loc[(
        population_map_attr['population'] == pop_type)]

    lat = float(52.48)
    lon = float(-1.89)
    zoom = float(8.5)

    layout = dict(
        mapbox=dict(
            layers=[],
            accesstoken=mapbox_access_token,
            center=dict(lat=lat, lon=lon),
            zoom=zoom,
        ),
        hovermode="closest",
        margin=dict(r=0, l=0, t=0, b=0),
        dragmode="lasso",
        uirevision="The User is always right",
    )

    at_risk_map_attr = access_map_attr.copy(deep=True)
    at_risk_oa_list = list(
        filter_extreme_oa(selected_access_data, selected_pop_data,
                          access_slider, population_slider))
    at_risk_map_attr['value'] = at_risk_map_attr['oa_id'].isin(
        at_risk_oa_list).astype(int)

    data = [
        go.Choroplethmapbox(geojson=oa_boundaries,
                            locations=at_risk_map_attr['oa_id'],
                            z=at_risk_map_attr['value'],
                            colorscale='oranges',
                            reversescale=False,
                            zmin=False,
                            zmax=True,
                            marker_opacity=at_risk_map_attr['value'],
                            marker_line_width=0,
                            showscale=False)
    ]

    return go.Figure(data=data, layout=layout)
def choropleth_coronavirus(csv_file):
    europe_url = 'https://raw.githubusercontent.com/leakyMirror/'+\
    'map-of-europe/master/GeoJSON/europe.geojson'
    jdata = read_geojson(europe_url)              
    jdata['features'][26]['properties']['NAME'] = 'Macedonia'
    ids = [feat['id'] for feat in jdata['features']]
    names = [feat['properties']['NAME'] for feat in jdata['features']]
    d = dict(zip(names, ids))
    df = pd.read_csv(csv_file)
    countries = list(df['European Region'])
    cids = [d[country]  for country in countries]

    df['cids'] = cids
    dfs = df.sort_values(by=['cids'])
    jdata['features'][26]['properties']['NAME'] = 'Macedonia'
    #my mapbox_access_token
    mapboxt = open(".mapbox_token").read().rstrip()
    locations = dfs['cids'].tolist()
    z = [np.log (cf+0.001) for   cf in dfs['total confirmed']]
    
    fig = go.Figure(go.Choroplethmapbox(
                                z=z,
                                locations=locations,
                                coloraxis='coloraxis',
                                geojson=jdata,
                                marker_line_width=0.75, 
                                marker_line_color='#eeeeee',
                                marker_opacity=0.85))
                            
                            
    fig.update_layout(width=1000, height=800,
                      font_family='Balto',
                      coloraxis=dict(colorscale='Reds',
                                     showscale=False),
                  
                      mapbox = dict(center= dict(lat= 55.499998,  
                                                 lon=17.3833318),
                                    accesstoken= mapboxt,
                                    zoom=2.55,
                                    style='basic'
                               ))

    fig.data[0].customdata = np.stack((dfs['European Region'],
                                       dfs['total confirmed'], 
                                       dfs['total deaths'], 
                                       dfs['transmission']), axis=-1)
    fig.data[0].hovertemplate = \
         "<b>%{customdata[0]}</b>"+\
         "<br><b>Total confirmed cases</b>: %{customdata[1]}"+\
         "<br><b>Total deaths </b>: %{customdata[2]}"+\
         "<br><b>Transmission </b>: %{customdata[3]}<extra></extra>"
    return fig
示例#20
0
def display_map(hg, sw_data_json, gw_data_json, s_info_json):
    s_info = pd.read_json(s_info_json, orient='split')
    if hg == 'Groundwater':
        s_data = ast.literal_eval(gw_data_json)
    else:
        s_data = ast.literal_eval(sw_data_json)

    sp_names = [n['id'] for n in s_data['features']]

    t_data = s_info[s_info.SpatialUnitName.isin(sp_names)]
    fig = go.Figure(go.Choroplethmapbox(geojson=s_data, locations=t_data['SpatialUnitName'], z=t_data.index, colorscale=t_data['color'].tolist(), zmin=t_data.index.min(), zmax=t_data.index.max(), marker_opacity=0.7, marker_line_width=0, showscale=False), layout=map_layout)

    return fig
示例#21
0
def generate_choropleth(time_values, selector, segment, kategori):

    if time_values is not None:
        min_date, max_date = time_slider_to_date(time_values)

        filtered_df = retailer_df.sort_values("Siparis_Tarihi").set_index(
            "Siparis_Tarihi")[min_date:max_date]

        filtered_df = filtered_df[filtered_df["Segment"].isin(segment)
                                  & filtered_df["Kategori"].isin(kategori)]

        df = pd.DataFrame(
            filtered_df.groupby(["Plaka_kodu"]).sum().reset_index())
        # print(df.head(10))
        # hovertemplate = "<br> %{z} TL"

        if selector == "siparis":
            z_val = "Siparis_Miktari"
        elif selector == "satis":
            z_val = "Satis"
        else:
            z_val = "Kar"

        fig = go.Figure(
            go.Choroplethmapbox(
                geojson=tr_sehirler,
                locations=df.Plaka_kodu,
                z=df[z_val],
                colorscale=[[0, "#65aaf7"], [1, "#012d6b"]],
                colorbar=dict(thickness=20, ticklen=3),
                #hovertemplate = hovertemplate,
                #hoverinfo=z,
                zmin=df[z_val].min(),
                zmax=df[z_val].max(),
                below=True,
                marker_opacity=0.6,
                marker_line_width=0.2))

        fig.update_layout(mapbox_style="carto-positron",
                          mapbox_zoom=4.5,
                          mapbox_center={
                              "lat": 39.822060,
                              "lon": 34.808132
                          })

        fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

        return fig

    return {"data": []}
示例#22
0
def update_graph(metric):

    if metric == 'Confirmed':
        #cs = "reds"
        cs = "inferno"
        rs = True
    elif metric == 'Active':
        #cs = "blues"
        cs = "plotly3"
        rs = False
    elif metric == 'Recovered':
        #cs = "greens"
        cs = "viridis"
        rs = False
    else:
        #cs = "oranges"
        cs = "RdYlGn"
        rs = False

    fig = go.Figure(
        go.Choroplethmapbox(geojson=indian_states,
                            locations=indian_map_data.fid.tolist(),
                            z=indian_map_data[metric].tolist(),
                            featureidkey="id",
                            hovertext=indian_map_data['hovertext'],
                            colorscale=cs,
                            reversescale=rs,
                            zmin=indian_map_data[metric].min(),
                            zmax=indian_map_data[metric].max(),
                            marker_opacity=0.8,
                            marker_line_width=1))
    fig.update_layout(mapbox_style="carto-positron",
                      mapbox_zoom=4.22,
                      mapbox_center={
                          "lat": 22.5458,
                          "lon": 82.0882
                      },
                      xaxis=dict(fixedrange=True),
                      yaxis=dict(fixedrange=True),
                      dragmode=False)
    fig.update_layout(height=800,
                      width=800,
                      margin={
                          "r": 0,
                          "t": 0,
                          "l": 0,
                          "b": 0
                      })

    return fig
示例#23
0
def mapa_comunas(request):

    fecha_ult_act_chile = data_crec_por_dia.columns[-1]

    fig = go.Figure(
        go.Choroplethmapbox(
            geojson=geo_comunas,
            locations=data_comunas.Comuna,
            z=data_comunas.Casos,
            colorscale="Viridis",
            zmin=0,
            zmax=1000,
            featureidkey="properties.NOM_COM",
            colorbar=dict(thickness=20, ticklen=3),
            marker_opacity=0.2,
            marker_line_width=0,
            text=data_comunas['Poblacion'],
            hovertemplate='<b>Región</b>: <b>' + data_comunas['Region'] +
            '</b>' + '<br><b>Comuna </b>: %{properties.NOM_COM}<br>' +
            '<b>Población: </b>:%{text}<br>' + '<b>Casos </b>: %{z}<br>'))
    fig.update_layout(mapbox_style="carto-positron",
                      mapbox_zoom=3,
                      height=600,
                      mapbox_center={
                          "lat": -30.0000000,
                          "lon": -71.0000000
                      })
    fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

    fig2 = casos_regiones_ac_act()

    graph1 = fig.to_html(full_html=False)
    graph2 = fig2.to_html(full_html=False)

    fig3 = grafico_Update_Dropdown_chile()
    graph3 = fig3.to_html(full_html=False)

    return render(
        request, "mapa_casos_comunas.html", {
            "fecha_Act_chile": fecha_ult_act_chile,
            "fecha_comuna": fecha,
            "num_recuFIS": num_recuFIS,
            "grafico1": graph1,
            "grafico2": graph2,
            "grafico3": graph3,
            "fecha_casos": fecha_casos,
            "n_casos": num_cases_cl,
            "num_rec": casos_act,
            "num_death": num_death
        })
示例#24
0
def dibujar_mapa(primer_ageb):
    primer_ageb_str = str(primer_ageb)
    geodf_jdata = obtenergeo_json_df(dataframe, geodataframe, 'CVE_AGEB',
                                     primer_ageb)

    geodf = geodf_jdata[0]
    jdata = geodf_jdata[1]

    z = geodf[primer_ageb_str].tolist()

    locations = geodf['CVE_AGEB'].tolist()

    trace_mapa = go.Choroplethmapbox(z=z,
                                     locations=locations,
                                     colorscale='magma',
                                     colorbar={
                                         'thicknessmode': 'pixels',
                                         'thickness': 7,
                                         'outlinecolor': 'white',
                                         'title': {
                                             'text': 'km',
                                             'side': 'bottom'
                                         }
                                     },
                                     reversescale=True,
                                     geojson=jdata,
                                     hoverinfo='location',
                                     marker_line_width=0.1,
                                     marker_opacity=0.7)

    layout_mapa = go.Layout(mapbox={
        'center': {
            'lat': 19.404730,
            'lon': -99.172845
        },
        'style': 'carto-positron',
        'zoom': 12
    },
                            margin={
                                'l': 0,
                                'r': 0,
                                't': 5,
                                'b': 15
                            },
                            clickmode='event+select')

    figura_mapa = go.Figure(data=[trace_mapa], layout=layout_mapa)

    return figura_mapa
def info_por_municipio(municipios):
    data =[]
    # print(municipios)
    df = get_filtered_rows(municipios)
    # print(df)
    data.append(go.Choroplethmapbox(
                geojson=geojson,
                locations=df['MPIOS'],
                z=df['HECTARES'],
                colorscale='earth',
                text=df['NOMBRE_MPI'],
                colorbar_title="HECTAREAS"
            ))
    # print(data)
    return data
示例#26
0
def juris_highlighter(juris_name):
    df['selected']=0
    df.loc[df['jurisdiction']==juris_name, 'selected']=1
    fig = go.Figure(go.Choroplethmapbox(geojson=counties,
                                        locations=df['FIPS'],
                                        z=df['selected'],
                                        colorscale=['Gray', 'Yellow'],
                                        # text=df['county_name'],
                                        zmin=0,
                                        zmax=1,
                                        marker_line_width=.5))
    fig.update_layout(mapbox_style="carto-positron",
                      mapbox_zoom=5.8,
                      mapbox_center = {"lat": 38.0293, "lon": -79.4428})
    fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
示例#27
0
def display_predictions():

    mapbox_key = "pk.eyJ1IjoicGxvdGx5bWFwYm94IiwiYSI6ImNqdnBvNDMyaTAxYzkzeW5ubWdpZ2VjbmMifQ.TXcBE-xg9BFdV2ocecc_7g"

    database = Connection()
    predicted_merged_2 = prediction_pull(database)
    colors = ["blue", "purple", "red"]
    with urlopen(
            'https://raw.githubusercontent.com/mikeypatt/json_file_crime/master/LSOA_2011.json'
    ) as response:
        j_file = json.load(response)

    i = 1
    for feature in j_file["features"]:
        feature['id'] = str(i).zfill(2)
        i += 1

    print(j_file["features"])
    print(predicted_merged_2['id'])

    fig = go.Figure(
        go.Choroplethmapbox(geojson=j_file,
                            locations=predicted_merged_2.id,
                            z=predicted_merged_2.prediction,
                            showscale=False,
                            colorscale=colors,
                            zmin=0,
                            zmax=20,
                            ids=predicted_merged_2.LSOA11NM,
                            text=predicted_merged_2.LSOA11NM,
                            hoverinfo='z+text'))
    fig.update_layout(mapbox_style="dark",
                      mapbox_accesstoken=mapbox_key,
                      mapbox_zoom=10,
                      mapbox_center={
                          "lat": 51.5074,
                          "lon": -0.1278
                      })
    fig.update_layout(autosize=True,
                      height=1300,
                      margin={
                          "r": 0,
                          "t": 0,
                          "l": 0,
                          "b": 0
                      })

    return fig
示例#28
0
def map_prep(geojson, locations, z, hovertext, center_lon, center_lat, zoom,
             title, updatetime):

    # prepare token for Mapbox
    token = 'pk.eyJ1IjoiY2h1emhpY29uZyIsImEiOiJjazZoMG5tajIwNmh4M21ueGN0eXdtMmx6In0.kQscrYmKzfyLhN-YgENO0Q'

    data = go.Choroplethmapbox(
        geojson=geojson,
        locations=locations,
        z=z,
        hovertext=hovertext,
        hoverinfo='text',
        colorscale='YlOrRd',
        marker_line_width=0.5,
        marker_line_color='rgb(169, 164, 159)',
        colorbar=dict(title="确诊病例数",
                      titleside="top",
                      tickmode="array",
                      tickvals=np.arange(0, 5, 1),
                      ticktext=["1", "10", "100", "1k", '10k', '100k'],
                      ticks="outside"))

    layout = go.Layout(mapbox={
        'accesstoken': token,
        'center': {
            'lon': center_lon,
            'lat': center_lat
        },
        'zoom': zoom
    },
                       margin={
                           "r": 1,
                           "t": 45,
                           "l": 45,
                           "b": 30
                       },
                       title='累计确诊' + title + '分布图',
                       annotations=[
                           dict(x=0.55,
                                y=0.03,
                                xref='paper',
                                yref='paper',
                                text='数据更新于 ' + str(updatetime),
                                showarrow=False)
                       ],
                       height=500)

    return data, layout
示例#29
0
def juris_highlighter(juris_name):
    df['selected']=np.where(df['jurisdiction']==juris_name, 1, 0)
    fig = go.Figure(go.Choroplethmapbox(geojson=counties,
                                        locations=df['FIPS'],
                                        z=df['selected'],
                                        # colorscale=['blues'],
                                        text=df['county_name'],
                                        hoverinfo='text',
                                        zmin=0,
                                        zmax=1,
                                        marker_line_width=.5
                                        ))
    fig.update_layout(mapbox_style="carto-positron",
                      mapbox_zoom=5.8,
                      mapbox_center = {"lat": 38.0293, "lon": -79.4428})
    fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
    return fig
示例#30
0
def update_map_fig(county, state):
    map_fig = go.Figure(
        go.Choroplethmapbox(geojson=counties,
                            locations=df["FIPS"],
                            z=df["10/2/20"],
                            colorscale="Viridis",
                            marker_opacity=0.5,
                            marker_line_width=0,
                            hovertext=hovertext))
    map_fig.update_layout(mapbox_style="carto-positron",
                          mapbox_zoom=3,
                          mapbox_center={
                              "lat": 37.0902,
                              "lon": -95.7129
                          },
                          margin=dict(l=20, r=20, t=20, b=20))
    return map_fig