如何在 plotly-dash 应用程序中绘制图表

How to Plot a graph inside plotly-dash app

我是 dash 的新手,我有一个可以在 dash-plotly 应用程序外绘制的图,但无法在 dash 应用程序内绘制相同的图。这是我的 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
from plotly.offline import iplot
import pandas as pd
import numpy as np

# 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()

# 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)

# set up plotly figure
fig = go.Figure()

# add one trace per NAR type and show counts per hospital
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['NAR 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>',
                    )
            )


fig.show()

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'
    ),
    dcc.Dropdown(
                id="Hosp_list",
                options=[{"label": i, "value": i} for i in hosp_list],
                multi=True,
                value=list(),

        )
])





if __name__ == '__main__':
    app.run_server(debug=True)

我确实喜欢在破折号 dcc.graph 部分显示相同的条形图。如您所见,dash 应用程序外部的代码运行并给出了绘图,但我不确定如何在 dash 应用程序内部实现相同的代码。请协助我在破折号应用程序中绘制此图

我重新编写了您的代码,使其 运行 并在 Dash 中呈现了一个绘图。但是,如果使用下拉菜单,我会跳过情节应该改变的部分。因此,您仍然必须在下拉回调中相应地更改绘图(请参阅 TODO)。如果用户更改下拉菜单,则会调用此函数。

我在您的代码中更改了两处。您可以设置图形的 'figure' 属性 而不是使用 fig.show。第二件事是在 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)