python - 如何对 Dash Plotly 中的各种图表执行向下钻取操作?
问题描述
我正在尝试对 Dash Plotly 中的各种图表执行向下钻取操作,但我找不到任何提供的教程或文档。
我尝试了一些来自 YouTube 的教程和一些从 google 阅读的文档,但是没有一种正确的代码方式可以真正满足我的要求。
要求是当用户单击条形图中的条形时,它应该在同一位置显示另一个条形图,表示内层数据。提前致谢!
解决方案
在 callback_context 的帮助下查看这个在 Dash 中向下钻取的示例。
在这个例子中,我只展示了一个单级向下钻取以保持简单,但只需进行少量修改,就可以实现多级向下钻取。有一个返回按钮可以返回到原始图形。后退按钮仅在向下钻取的第二层显示并隐藏在原始底层。
代码:
import dash
import dash_core_components as dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
# creating a dummy sales dataframe
product_sales = {'vendors':['VANS','VANS','VANS','VANS','NIKE','NIKE','NIKE','ADIDAS','ADIDAS','CONVERSE','CONVERSE','CONVERSE'],
'products': ['Tshirts','Sneakers','Caps','Clothing','Sports Outfit','Sneakers','Caps','Accessories','Bags','Sneakers','Accessories','Tshirts'],
'units sold': [2,15,3,8,37,13,7,4,12,7,8,2]
}
product_sales_df = pd.DataFrame(product_sales)
# all vendors sales pie chart
def sales_pie():
df = product_sales_df.groupby('vendors').sum().reset_index()
fig = px.pie(df, names='vendors',
values='units sold', hole=0.4)
fig.update_layout(template='presentation', title='Sales distribution per Vendor')
return fig
# creating app layout
app.layout = dbc.Container([
dbc.Card([
dbc.Button('', id='back-button', outline=True, size="sm",
className='mt-2 ml-2 col-1', style={'display': 'none'}),
dbc.Row(
dcc.Graph(
id='graph',
figure=sales_pie()
), justify='center'
)
], className='mt-3')
])
#Callback
@app.callback(
Output('graph', 'figure'),
Output('back-button', 'style'), #to hide/unhide the back button
Input('graph', 'clickData'), #for getting the vendor name from graph
Input('back-button', 'n_clicks')
)
def drilldown(click_data,n_clicks):
# using callback context to check which input was fired
ctx = dash.callback_context
trigger_id = ctx.triggered[0]["prop_id"].split(".")[0]
if trigger_id == 'graph':
# get vendor name from clickData
if click_data is not None:
vendor = click_data['points'][0]['label']
if vendor in product_sales_df.vendors.unique():
# creating df for clicked vendor
vendor_sales_df = product_sales_df[product_sales_df['vendors'] == vendor]
# generating product sales bar graph
fig = px.bar(vendor_sales_df, x='products',
y='units sold', color='products')
fig.update_layout(title='<b>{} product sales<b>'.format(vendor),
showlegend=False, template='presentation')
return fig, {'display':'block'} #returning the fig and unhiding the back button
else:
return sales_pie(), {'display': 'none'} #hiding the back button
else:
return sales_pie(), {'display':'none'}
if __name__ == '__main__':
app.run_server(debug=True)
另请查看此线程以获取更多信息。
推荐阅读
- java - 热到使 InputStream - 阅读器转换?
- python - 按日期输入请求破坏的数据比较工具:
- assembly - 用汇编返回字符输入?
- tensorflow - 如何显示 tf.Variable 的内容
- python - 为什么我在 Python Shell 中出现此语法错误但没有 Pycharm IDE?
- azure-devops - 谁可以覆盖 Azure Pipelines 中发布阶段的批准?
- java - Java StringTokenizer.countTokens() 的时间复杂度是多少
- python - 如何检查矩阵是否在矩阵列表中 Python
- sql - 如果,PL SQL 中的 ELSIF 和 ELSE 条件不起作用
- javascript - 如何使用 libphonenumber AsYouTypeFormatter 处理退格