python - 如何使用回调来更新 Dash 中的条形图
问题描述
由于 Dash 是用于制作基于 Web 的交互式图表的相当新的框架,因此对于初学者来说没有太多具体或详细的信息。就我而言,我需要使用回调函数更新一个简单的条形图。即使服务器运行良好而没有提示任何错误,数据也不会在浏览器上呈现。
需要帮助整理和理解数据不呈现的原因。
import dash
from dash.dependencies import Output, Event
import dash_core_components as dcc
import dash_html_components as html
import plotly
import plotly.graph_objs as go
app = dash.Dash(__name__)
colors = {
'background': '#111111',
'background2': '#FF0',
'text': '#7FDBFF'
}
app.layout = html.Div( children = [
html.Div([
html.H5('ANNx'),
dcc.Graph(
id='cx1'
)
])
]
)
@app.callback(Output('cx1', 'figure'))
def update_figure( ):
return {
'data': [
{'x': ['APC'], 'y': [9], 'type': 'bar', 'name': 'APC'},
{'x': ['PDP'], 'y': [8], 'type': 'bar', 'name': 'PDP'},
],
'layout': {
'title': 'Basic Dash Example',
'plot_bgcolor': colors['background'],
'paper_bgcolor': colors['background']
}
}
if __name__ == '__main__':
app.run_server(debug=True)
解决方案
您可以通过这种方式使用回调(我为此创建了下拉菜单):
import dash
from dash.dependencies import Output, Input
import dash_core_components as dcc
import dash_html_components as html
import plotly
import plotly.graph_objs as go
import pandas as pd
app = dash.Dash(__name__)
df = pd.DataFrame({'x': ['APC', 'PDP'], 'y': [9, 8]})
colors = {
'background': '#111111',
'background2': '#FF0',
'text': '#7FDBFF'
}
app.layout = html.Div(children=[
html.Div([
html.H5('ANNx'),
html.Div(
id='cx1'
),
dcc.Dropdown(id='cx2',
options=[{'label': 'APC', 'value': 'APC'},
{'label': 'PDP', 'value': 'PDP'},
{'label': 'Clear', 'value': None}
]
)
])])
@app.callback(Output('cx1', 'children'),
[Input('cx2', 'value')])
def update_figure(value):
if value is None:
dff = df
else:
dff = df.loc[df["x"] == value]
return html.Div(
dcc.Graph(
id='bar chart',
figure={
"data": [
{
"x": dff["x"],
"y": dff["y"],
"type": "bar",
"marker": {"color": "#0074D9"},
}
],
"layout": {
'title': 'Basic Dash Example',
"xaxis": {"title": "Authors"},
"yaxis": {"title": "Counts"},
'plot_bgcolor': colors['background'],
'paper_bgcolor': colors['background']
},
},
)
)
if __name__ == '__main__':
app.run_server(debug=True)
推荐阅读
- c# - 是否可以在 Entity Framework Core 2.1 版上自动映射数据库视图?
- liquid - 如何从 Shopify 主题中的“产品”输入中获取产品 URL
- laravel - GraphQL GroupBy
- html - Prevent collapsed navbar from pushing content below
- visual-studio - Visual Studio 2017 更改垂直滚动中选定引用的颜色
- c - wcscmp - 使用此函数时访问冲突
- qt - Jenkins: CMake Error at /usr/local/share/cmake-3.11/Modules/FindProtobuf.cmake
- ios - 在 Xcode 中更改团队并将应用程序转移到公司帐户
- c++ - c++ boost::thread() in Qt application - error: too many arguments to function
- python - 避免在执行前内置输入来读取标准输入