✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🧬 Learn how to build RNA-Seq data apps with Python & Dash. Register for the May 20 Webinar!

Creating another chart using the same dropdown

Execuse me, I created my first chart with these dropdowns. Now, I’d like to add another chart in the same page with the same dropdowns. here is the code I wrote

import dash
import dash_html_components as html
import dash_core_components as dcc
import plotly.graph_objs as go
import pandas as pd
from dash.dependencies import Input, Output

df = pd.read_csv('redcap.csv')

app = dash.Dash()

app.config['suppress_callback_exceptions'] = True

year_options = []
for year in df['year'].unique():
    year_options.append({'label': str(year), 'value': year})

unit_options = []
for unit in df['unit'].unique():
    unit_options.append({'label': str(unit), 'value': unit})


app.layout = html.Div([
    html.Div([
        dcc.Dropdown(id='year_picker', options=year_options,
                     value=df['year'].min())
    ],
        style={'width': '48%', 'display': 'inline-block'}),
    html.Div([
        dcc.Dropdown(id='unit_picker', options=unit_options,
                     value=df['unit'])
    ],
        style={'width': '48%', 'float': 'right', 'display': 'inline-block'}),
    dcc.Graph(id='nursing titles')
], style={'padding': 10})


@app.callback(Output('nursing titles', 'figure'),
              [Input('year_picker', 'value'),
               Input('unit_picker', 'value')])
def titles(year, unit):
    dff = df[(df['year'] == year) & (df['unit'] == unit)]
    count = dff['title'].value_counts().reset_index()
    labels = count['index'].astype(str).tolist()
    values = count['title'].tolist()
    data = go.Pie(labels=labels,
                  values=values,
                  textinfo='value+percent',
                  textposition='inside',
                  direction='clockwise',
                  sort=False)
    layout = go.Layout(title='Post Distribution {}'.format(year))
    fig = go.Figure(data=data, layout=layout)
    return fig


app.layout = html.Div([
    dcc.Graph(id='nursing gender')
], style={'padding': 10})


@app.callback(Output('nursing gender', 'figure'),
              [Input('year_picker', 'value'),
               Input('unit_picker', 'value')])
def gender(year, unit):
    dfff = df[(df['year'] == year) & (df['unit'] == unit)]
    count = dfff['gender'].value_counts().reset_index()
    labels = count['index'].astype(str).tolist()
    values = count['gender'].tolist()
    data = go.Pie(labels=labels,
                  values=values,
                  textinfo='value+percent',
                  textposition='inside',
                  direction='clockwise',
                  sort=False)
    layout = go.Layout(title='Gender Distribution {}'.format(year))
    fig = go.Figure(data=data, layout=layout)
    return fig


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

and here is a screenshot that may help imagine

Remove the code below:

app.layout = html.Div([
    dcc.Graph(id='nursing gender')
], style={'padding': 10})

and insert the dcc.Graph into the app.layout previously defined:

app.layout = html.Div([
    html.Div([
        dcc.Dropdown(id='year_picker', options=year_options,
                     value=df['year'].min())
    ],
        style={'width': '48%', 'display': 'inline-block'}),
    html.Div([
        dcc.Dropdown(id='unit_picker', options=unit_options,
                     value=df['unit'])
    ],
        style={'width': '48%', 'float': 'right', 'display': 'inline-block'}),
    dcc.Graph(id='nursing titles'),
    dcc.Graph(id='nursing gender'),
], style={'padding': 10})

Hi @flyingcujo, I’d like to style this page [a problem in the image that doesn’t appear], here is my code

import dash
import dash_html_components as html
import dash_core_components as dcc
import plotly.graph_objs as go
import pandas as pd
import numpy as np
from dash.dependencies import Input, Output

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.renderer = 'var renderer = new DashRenderer();'
app.index_string = '''
<!DOCTYPE html>
<html>
    <head>
        {%metas%}
        <title>AHC Nursing</title>
        {%favicon%}
        {%css%}
    </head>
    <body>
        {%app_entry%}
        <footer>
            {%config%}
            {%scripts%}
            {%renderer%}
        </footer>
    </body>
</html>
'''
app.config['suppress_callback_exceptions'] = True


def Header():
    return html.Div([
        get_logo(),
        get_header(),
        html.Br([])
    ])


def get_logo():
    logo = html.Div([

        html.Div([
            html.Img(src='./logo2.png', height='101', width='141')
        ], className="ten columns padded"),

    ], className="row gs-header")
    return logo


def get_header():
    header = html.Div([

        html.Div([
            html.H5(
                'AHC Nursing Department Staff Audit', is_loading= True)
        ], className="twelve columns padded")

    ], className="row gs-header gs-text-header")
    return header


df = pd.read_csv(
    r'D:\Data Science\Interactive Python Dashboards with Plotly and Dash\github_repo\tutorial\redcap.csv', encoding="ISO-8859-1")
# df['started_at_ahc'] = pd.to_datetime(df['started_at_ahc'])
# df['experience_y'] = round(
#     (pd.Timestamp.now() - df['started_at_ahc']) / np.timedelta64(1, 'Y'), 0)
# df['experience_m'] = round(
#     (pd.Timestamp.now() - df['started_at_ahc']) / np.timedelta64(1, 'M'), 0)

year_options = []
for year in df['year'].unique():
    year_options.append({'label': str(year), 'value': year})

unit_options = []
for unit in df['unit'].unique():
    unit_options.append({'label': str(unit), 'value': unit})


app.layout = html.Div([
    Header(),
    html.Div([
        html.Div([
            dcc.Dropdown(id='year_picker', options=year_options,
                         value=df['year'].max())
        ],
            style={'width': '48%', 'display': 'inline-block'}),
        html.Div([
            dcc.Dropdown(id='unit_picker', options=unit_options,
                         value=df['unit'])
        ],
            style={'width': '48%', 'float': 'right', 'display': 'inline-block'}),
        # dcc.Graph(id='titles'),
        # dcc.Graph(id='gender'),
        # dcc.Graph(id='qualification'),
        # dcc.Graph(id='old'),
        # dcc.Graph(id='housing'),
        # dcc.Graph(id='residence'),
        # dcc.Graph(id='english_level'),
        # dcc.Graph(id='medical_insurance'),
        # dcc.Graph(id='experience_level')
    ], style={'padding': 10})
])


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

but when running the app I got it like this

Hello.

You need to create a folder called assets at the same level as your app.py file. Place logo2.png in this folder and then change src=./logo2.png to src=/assets/logo2.png

See https://dash.plot.ly/external-resources for more details.