我正在使用plotly 绘制一个散点图框。底图工作正常,但点未渲染。如果我打印图像,点就会出现。如果我还将 .show() 添加到图中,则会有一个单独的链接显示这些点。但我希望下拉栏选择单个状态和要可视化的点。我不知道我做错了什么?
import dash
from dash import Dash, dcc, html, Input, Output
import dash_bootstrap_components as dbc
import plotly.express as px
import pandas as pd
import plotly.graph_objs as go
import numpy as np
mapboxtoken = "xxx"
us_cities = pd.read_csv(
'https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv'
)
stateID = us_cities['State'].unique()
external_stylesheets = [dbc.themes.SPACELAB, dbc.icons.BOOTSTRAP]
app = dash.Dash(__name__, external_stylesheets = external_stylesheets)
app.layout = html.Div([
dcc.Dropdown(id="states_select",
options=stateID,
optionHeight=25,
multi=True,
searchable=True,
placeholder='Please select...',
clearable=True,
value=[''],
style={'width': "60%"}
),
html.Div([
dcc.Graph(id="the_graph")
]),
])
@app.callback(
Output("the_graph", "figure"),
Input("states_select", "value"),
)
def update_graph(states_chosen):
dff = us_cities[us_cities["State"].isin(states_chosen)]
scatter = px.scatter_mapbox(data_frame = dff,
lat = 'lat',
lon = 'lon',
zoom = 0,
hover_data = ['State', 'lat', 'lon']
)
scatter.update_layout(
height = 750,
mapbox=dict(
style='carto-positron',
accesstoken=mapboxtoken,
),
margin={'r':10, 't': 0, 'l': 0, 'b': 0}
)
#scatter.show()
return scatter
if __name__ == '__main__':
app.run_server(debug=True, port = 8050)
代码中存在一个小错误导致了问题。
dcc.Graph
组件中缺少
figure
属性。你需要在
dcc.Graph
中初始化一个空白图形或默认图形,以便回调能够更新它。
以下是更新后的代码:
import dash
from dash import Dash, dcc, html, Input, Output
import dash_bootstrap_components as dbc
import plotly.express as px
import pandas as pd
import plotly.graph_objs as go
import numpy as np
mapboxtoken = "xxx"
us_cities = pd.read_csv(
'https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv'
)
stateID = us_cities['State'].unique()
external_stylesheets = [dbc.themes.SPACELAB, dbc.icons.BOOTSTRAP]
app = dash.Dash(__name__, external_stylesheets = external_stylesheets)
app.layout = html.Div([
dcc.Dropdown(id="states_select",
options=stateID,
optionHeight=25,
multi=True,
searchable=True,
placeholder='Please select...',
clearable=True,
value=[''],
style={'width': "60%"}
),
html.Div([
dcc.Graph(id="the_graph", figure={}) # <-- 添加 figure={}
]),
])
@app.callback(
Output("the_graph", "figure"),
Input("states_select", "value"),
)
def update_graph(states_chosen):
dff = us_cities[us_cities["State"].isin(states_chosen)]
scatter = px.scatter_mapbox(data_frame = dff,
lat = 'lat',
lon = 'lon',
zoom = 0,
hover_data = ['State', 'lat', 'lon']
)
scatter.update_layout(
height = 750,
mapbox=dict(
style='carto-positron',
accesstoken=mapboxtoken,
),
margin={'r':10, 't': 0, 'l': 0, 'b': 0}
)
return scatter
if __name__ == '__main__':
app.run_server(debug=True, port = 8050)
通过添加
figure={}
, 你就在
dcc.Graph
组件中创建了一个空的图形对象,回调函数可以更新它并将数据显示在网页上。