我是破折号的新手,我有一个绘图,可以在破折号绘图应用程序外进行绘图,但是无法在破折号应用程序内绘图相同的图形。这是我的破折号应用程序代码:
{1}
我想在破折号dcc.graph部分显示相同的条形图。如您所见,破折号应用程序外部的代码运行并给出了图表,但我不确定如何在破折号应用程序内部实现相同的代码。请协助我在仪表板应用程序中绘制此图
答案 0 :(得分:1)
我对您的代码进行了重新设计,以使其运行并在Dash中渲染图。但是,如果使用下拉菜单,我将跳过绘图应更改的部分。因此,您仍然必须在下拉回调中相应地更改绘图(请参见TODO)。如果用户更改下拉菜单,则会调用此函数。
我在您的代码中做了两件事。无需使用fig.show而是设置图形的'figure'属性。第二件事是全局变量不应该在Dash中使用,这就是为什么我将图形和数据框创建放入函数中的原因。
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objects as go
import pandas as pd
def create_df():
# intialise data of lists.
data = {'Name': ['Nick hospital', 'Nick hospital', 'Nick hospital', 'Krish hospital', 'Krish hospital',
'Krish hospital'],
'NAR_forms_used': [2, 1, 2, 2, 2, 3]}
# Create DataFrame
df = pd.DataFrame(data)
# get counts per NAR type
df_nar = pd.DataFrame(df.groupby('Name')['NAR_forms_used'].value_counts())
df_nar = df_nar.rename({'NAR_forms_used': 'Doc count'}, axis='columns')
df_nar = df_nar.reset_index()
return df_nar
def create_figure(df_nar):
# set up plotly figure
fig = go.Figure()
# Manage NAR types (who knows, there may be more types with time?)
nars = df_nar['NAR_forms_used'].unique()
nars = nars.tolist()
nars.sort(reverse=False)
# add one trace per NAR type and show counts per hospital
data = []
for nar in nars:
# subset dataframe by NAR type
df_ply = df_nar[df_nar['NAR_forms_used'] == nar]
# add trace
fig.add_trace(go.Bar(x=df_ply['Name'], y=df_ply['Doc count'], name='NAR Type=' + str(nar)))
# make the figure a bit more presentable
fig.update_layout(title='NAR per hospital',
yaxis=dict(title='<i>count of NAR types</i>'),
xaxis=dict(title='<i>Hospital</i>'))
return fig
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.Graph(id='graph', figure=create_figure(create_df())),
dcc.Dropdown(
id="Hosp_list",
options=[{"label": i, "value": i} for i in create_df()['Name'].tolist()],
multi=True,
value=list(),
)
])
@app.callback(
Output('graph', 'figure'),
[Input('Hosp_list', 'value') ])
def dropdown_changed(values):
# TODO:
# build a graph depending on the dropdown selection (parameter values) and
# return it instead of dash.no_update (which prevents update of client)
print('Dropdown triggered with these values:', values)
return dash.no_update
if __name__ == '__main__':
app.run_server(debug=True)