我一直在嘗試使用 Dash 和 Plotly 構建互動式破折號
我有幾個下拉選單允許用戶選擇過濾器,但是我的圖表和餅圖只顯示過濾后的資料,當我清除過濾器以向用戶展示完整的資料分析時,圖表和圖表不起作用并且回傳空圖
有什么建議我應該如何使用我的update_chart函式構建或更改完整分析的完整資料集以分別反映過濾/未過濾的資料?
我data從 Firestore 得到我的,您可以假設資料沒有問題(已驗證)
這是我的代碼:
html
html.Div(
children=[
html.Div(
children=[
html.Div(children="State", className="menu-title"),
dcc.Dropdown(
id="state-filter",
options=[
{"label": state, "value": state}
for state in np.sort(data.state.unique())
],
value="CA",
clearable=True,
className="dropdown",
),
]
),
html.Div(
children=[
html.Div(children="Category", className="menu-title"),
dcc.Dropdown(
id="category-filter",
options=[
{"label": category, "value": category}
for category in data.category.unique() if not pd.isnull(category)
],
value="web",
clearable=True,
className="dropdown",
),
]
),
html.Div(
children=[
html.Div(
children="Date Range", className="menu-title"
),
dcc.DatePickerRange(
id="date-range",
min_date_allowed=data.fundedDate.min().date(),
max_date_allowed=data.fundedDate.max().date(),
start_date=data.fundedDate.min().date(),
end_date=data.fundedDate.max().date(),
),
]
),
],
className="menu",
),
html.Div(
children=[
html.Div(
children=dcc.Graph(
id="funding-chart",
config={"displayModeBar": False},
),
className="card",
),
html.Div(
children=dcc.Graph(
id="category-chart",
figure={},
className='six columns',
),
),
],
className="wrapper",
),
資料
@dash_app.callback(
[Output("funding-chart", "figure"), Output("category-chart", "figure")],
[
Input("state-filter", "value"),
Input("category-filter", "value"),
Input("date-range", "start_date"),
Input("date-range", "end_date"),
],
)
def update_charts(state, category, start_date, end_date):
mask = (
(data.state == state)
& (data.category == category)
& (data.fundedDate >= start_date)
& (data.fundedDate <= end_date)
)
filtered_data = data.loc[mask, :]
funding_chart_figure = {
"data": [
{
"x": filtered_data["fundedDate"],
"y": filtered_data["raisedAmt"],
"type": "lines",
"hovertemplate": "$%{y:.2f}<extra></extra>",
},
],
"layout": {
"title": {
"text": "Raised fundings by date",
"x": 0.05,
"xanchor": "left",
},
"xaxis": {"fixedrange": True},
"yaxis": {"tickprefix": "$", "fixedrange": True},
"colorway": ["#17B897"],
},
}
category_chart_figure = px.pie(data_frame=filtered_data, values='raisedAmt',
names='category', title='Raised funding by category')
return funding_chart_figure, category_chart_figure
過濾資料時

當我想清除過濾器并獲得分析概述時,該filtereddata設定導致我無法取回完整資料

調整我的update_chart功能以實作我想要的任何好主意?謝謝
uj5u.com熱心網友回復:
如果我理解正確,問題是“類別”為空,這會導致過濾器損壞。
在 update_charts 開頭的 if 陳述句中捕捉這種情況怎么樣?
#[...]
def update_charts(state, category, start_date, end_date):
category_filter = True #get all categories if category is empty
if category:
category_filter = (data.category == category)
mask = (
(data.state == state)
& category_filter
& (data.fundedDate >= start_date)
& (data.fundedDate <= end_date)
)
#[...]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/432456.html
上一篇:PulumiAutomationAPI不運行PulumiCLI?
下一篇:查看python中所有繼承的類
