1

I am new to dash and I have a plot which I can plot outside dash-plotly app but am unable to plot the same graph inside dash app. Here is my dash app code:

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)

I did like to display the same bar graph on dash dcc.graph section. As you can see the code outside dash app runs and gives the plot but I not sure how to implement the same inside dash app. Kindly assist me to plot this graph inside the dash app

1
  • just add figure = fig in dcc.Graph.
    – Frayal
    Commented Jan 17, 2020 at 13:11

1 Answer 1

1

I reworked your code so that it is running and renders a plot in Dash. I however skipped the part where the plot should change if the dropdown is used. So you still have to change the plot accordingly in the dropdown callback (see the TODO). This function gets called if the user changes the dropdown menu.

There are two things that I changed in your code. Instead of using fig.show you set the 'figure' property of your graph. The second thing is that global variables shouldn't be used in Dash, this is why I put your figure and dataframe creation into functions.

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)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.