dcc.Loading on First Load (Python)

问题描述

我正在开发一个 Plotly Dash 项目,该项目有很多经过过滤、切片和切块的等值线图。这些是非常昂贵的计算,会减慢一切,所以我认为这是一个很好的接触,我可以在地图周围添加一个 dcc.loading 包装器,至少让用户知道它正在加载,而不是我的仪表板看起来滞后。

我遇到的问题是每次更改地图后都会出现加载图标。即使是不到 1 秒的快速更改,也会出现加载图标。我的挑战是我仍想使用 dcc.loading 包装器,但让它仅在地图的初始加载时显示

我正在 Plotly 社区网站上阅读这篇解决相同问题的博客,但没有人能够想出解决方案:https://community.plotly.com/t/loading-states-and-loading-component/19650/35。此外,我在此处使用 Dash 帮助页面中的“PreventUpdate”参数:https://dash.plotly.com/advanced-callbacks,但仍然找不到解决方案。

谁能帮我指明正确的方向?

这是一些示例代码

import pandas as pd
import dash
from urllib.request import urlopen
import json
import plotly.express as px
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input,Output 
#from dash.exceptions import PreventUpdate


with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
    counties = json.load(response)

df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",dtype={"fips": str})

fips_choices = df['fips'].sort_values().unique()


app = dash.Dash(__name__)
server = app.server
app.layout = html.Div([
    dcc.Dropdown(id='dropdown1',options=[{'label': i,'value': i} for i in fips_choices],value=fips_choices[0]
    ),dcc.Loading(
        id='loading',children=[
            dcc.Graph(id='us_map')
    ])
])



@app.callback(
    Output('us_map','figure'),Input('dropdown1','value'))

def update_map(county_select):
        new_df = df[df['fips']==county_select]
        fig = px.choropleth_mapBox(new_df,geojson=counties,locations='fips',color='unemp',color_continuous_scale="Viridis",range_color=(0,12),mapBox_style="carto-positron",zoom=3,center = {"lat": 37.0902,"lon": -95.7129},opacity=0.5
                          )
        fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})

        return fig

app.run_server(host='0.0.0.0',port='8051')

解决方法

dcc.Loading 可能没有办法

这是一个对我有用的解决方案。

给你的地图样式 {"display":"none"}

dcc.Graph(id="us_map",style={"display": "none"})

在回调中添加 us-map 样式作为输出并返回 {"display":"inline"}

@app.callback(
    [Output("us_map","figure"),Output("us_map","style")],Input("dropdown1","value")
)
def update_map(county_select):
    new_df = df[df["fips"] == county_select]
    fig = px.choropleth_mapbox(
        new_df,geojson=counties,locations="fips",color="unemp",color_continuous_scale="Viridis",range_color=(0,12),mapbox_style="carto-positron",zoom=3,center={"lat": 37.0902,"lon": -95.7129},opacity=0.5,)
    fig.update_layout(margin={"r": 0,"t": 0,"l": 0,"b": 0})

    return fig,{"display": "inline"} 

如果想要加载条而不是空白区域,将加载条放在地图上方的div中,将加载条作为输出添加到div中,添加aa return of {"display":"false"以便在地图加载时加载动画消失。你不能让它与 dcc.Loading 一起工作,所以我只使用了一个自定义的 CSS 加载栏。