【问题标题】:DASH dropdowns and graphDASH 下拉菜单和图表
【发布时间】:2021-09-17 14:21:40
【问题描述】:

我在根据 3 个下拉菜单更新地图时遇到问题。

我有 3 个下拉菜单:一个用于国家/地区,一个用于地区,一个用于类别。

当我一次选择 1 个下拉菜单时,我可以在地图上看到结果。

但我真正想要的是放大。所以当我选择国家然后选择地区时,我只想查看那个特定地区的结果。

现在,如果我从下拉列表中选择一个国家,然后从另一个下拉列表中选择一个类别,我会在地图上看到整个国家的结果。它不会将搜索范围缩小到所选类别。

    dbc.Col([
            html.Label("Select Country: ", style={'font-family': 'arial', 'font-weight': 'bold', 'font-size': 15, 'color': 'white'}),
            dcc.Dropdown(className='scrollable-element div-for-dropdown Select-control VirtualizedSelectOption',
                         id='country_dropdown',
                         options=[{'label': str(c), 'value': c} for c in sorted(df['Country'].unique())],
                         multi=True,
                         placeholder="Select",
                         value=['United Kingdom'],
                         clearable=True,
                         style={'width': '100%', 'font-family': 'arial', 'font-weight': 'bold', 'font-size': 13, 'color': 'black', 'background-color': '#31302F', 'border': '0px solid black'}
                         ),

            html.Br(),

            html.Label("Select District: ", style={'font-family': 'arial', 'font-weight': 'bold', 'font-size': 15, 'color': 'white'}),
            dcc.Dropdown(className='scrollable-element div-for-dropdown Select-control VirtualizedSelectOption',
                         id='district_dropdown',
                         multi=True,
                         value=[],
                         clearable=True,
                         options=[{'label': str(d), 'value': d} for d in sorted(df['MainLocation'].unique())],
                         placeholder="Select",
                         style={'width': '100%', 'font-family': 'arial', 'font-weight': 'bold', 'font-size': 13, 'color': 'black', 'background-color': '#31302F', 'border': '0px solid black'}
                         ),
            html.Br(),

            html.Label("Select Category: ", style={'font-family': 'arial', 'font-weight': 'bold', 'font-size': 15, 'color': 'white'}),
            dcc.Dropdown(className='div-for-dropdown Select-control VirtualizedSelectOption',
                         id='category_dropdown',
                         multi=True,
                         value=[],
                         clearable=True,
                         options=[{'label': '(Select All)', 'value': 'all'}] + [{'label': str(cat), 'value': cat} for cat in sorted(df['Category'].unique())],
                         placeholder="Select",
                         style={'width': '100%', 'font-family': 'arial', 'font-weight': 'bold', 'font-size': 13, 'color': 'black', 'background-color': '#31302F', 'border': '0px solid black'}
                         )


`@app.callback(Output('map_graph', 'figure'),
              [Input('country_dropdown', 'value'),
               Input('category_dropdown', 'value'),
               Input('district_dropdown', 'value')])

def update_map_graph(chosen_country, chosen_category, chosen_district):
    df_sub = df[(df['Country'].isin(chosen_country)) |
                (df['Category'].isin(chosen_category)) |
                (df['MainLocation'].isin(chosen_district))]

    # Create figure
    locations = [go.Scattermapbox(
        lon=df_sub['Long'],
        lat=df_sub['Lat'],
        mode='markers',
        marker={'color': df_sub['Color'], 'size': 13, 'opacity': 0.5},
        unselected={'marker': {'opacity': 1}},
        selected={'marker': {'opacity': 0.5, 'size': 18}},
        hoverinfo='text',
        hovertext=df_sub['Hover']
    )]

    # Return figure
    return {
        'data': locations,
        'layout': go.Layout(
            autosize=True,
            margin=dict(l=0,
                        r=0,
                        t=0,
                        b=0),
            uirevision='foo',
            clickmode='event+select',
            hovermode='closest',
            hoverdistance=2,
            mapbox=dict(
                accesstoken=mapbox_access_token,
                bearing=0,
                style='mapbox://styles/mapbox/navigation-night-v1',
                center=dict(
                    lat=50.1109,
                    lon=8.6821
                ),
                pitch=0,
                zoom=5
            ),
        )
    }`

【问题讨论】:

    标签: python dictionary plotly dropdown plotly-dash


    【解决方案1】:
    • 你没有提供样本数据,所以我使用了英国医院数据
    • 创建一个geopandas数据框,这样total_bounds就可以使用了
    • 渐进式直接构建下拉菜单。获取任何选择的几何中心
    import json
    import numpy as np
    import dash
    import plotly.graph_objects as go
    from dash.dependencies import Input, Output, State
    from jupyter_dash import JupyterDash
    import requests, io
    import pandas as pd
    import geopandas as gpd
    import shapely
    import plotly.express as px
    
    # get some public addressess - hospitals.  data that can be scattered
    dfhos = pd.read_csv(
        io.StringIO(
            requests.get("http://media.nhschoices.nhs.uk/data/foi/Hospital.csv").text
        ),
        sep="¬",
        engine="python",
    )
    
    fig = px.scatter_mapbox(
        dfhos, lat="Latitude", lon="Longitude", hover_data=["County", "City", "Address1"]
    ).update_layout(
        mapbox={"style": "carto-positron"}, margin={"l": 0, "r": 0, "t": 0, "b": 0}
    )
    
    # create a geo dataframe of hospitals
    gdfhos = gpd.GeoDataFrame(
        data=dfhos,
        geometry=dfhos.apply(
            lambda r: shapely.geometry.Point(r["Longitude"], r["Latitude"]), axis=1
        ),
        crs="EPSG:4326",
    )
    
    
    # Build App
    app = JupyterDash(__name__)
    app.layout = dash.html.Div(
        [
            dash.dcc.Dropdown(
                id="County",
                options=[
                    {"label": c, "value": c}
                    for c in dfhos["County"].dropna().sort_values().unique()
                ],
                value=None,
            ),
            dash.dcc.Dropdown(id="City", value=None),
            dash.dcc.Dropdown(id="Address1", value=None),
            dash.dcc.Graph(
                id="map",
                figure=fig,
            ),
        ],
    )
    
    
    @app.callback(
        [
            Output("map", "figure"),
            Output("City", "options"),
            Output("Address1", "options"),
        ],
        Input("County", "value"),
        Input("City", "value"),
        Input("Address1", "value"),
        State("map", "figure"),
    )
    def center_selection(county, city, address1, fig):
        city_out = []
        addr_out = []
        bb = gdfhos.geometry.total_bounds
        if county:
            bb = gdfhos.loc[gdfhos["County"].eq(county)].geometry.total_bounds
            city_out = [
                {"label": c, "value": c}
                for c in dfhos.loc[dfhos["County"].eq(county), "City"]
                .dropna()
                .sort_values()
                .unique()
            ]
        if county and city:
            bb = gdfhos.loc[
                gdfhos["County"].eq(county) & gdfhos["City"].eq(city)
            ].geometry.total_bounds
            addr_out = [
                {"label": c, "value": c}
                for c in dfhos.loc[
                    dfhos["County"].eq(county) & dfhos["City"].eq(city), "OrganisationName"
                ]
                .dropna()
                .sort_values()
                .unique()
            ]
    
        return (
            go.Figure(fig).update_layout(
                mapbox={"center": {"lon": (bb[0] + bb[2]) / 2, "lat": (bb[1] + bb[3]) / 2}}
            ),
            city_out,
            addr_out,
        )
    
    
    # Run app and display result inline in the notebook
    app.run_server(mode="inline")
    

    【讨论】:

    • 感谢您的回复。不使用 geopandas 是否可以做到这一点?
    • 是的 - 只需要计算可以在熊猫中完成的边界框。使用 geopandas 功能更方便
    猜你喜欢
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多