Skip to content Skip to sidebar Skip to footer

Unable To Show Graph When Dropdown List Is Cleared In Dash Plotly

I built a dash app to show scatter plot of total_bill vs tip from tips dataset. I have a dropdown menu that allows multiple selection of days, so that I can color the scatter plot

Solution 1:

This could be something like this (Dash v1.6.0):

import dash
import dash_html_components as html
import dash_core_components as dcc
import seaborn as sns
import plotly.express as px

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

tips = sns.load_dataset("tips")
all_days = ['Thur', 'Fri', 'Sat', 'Sun']

app.layout = html.Div([
    html.P('select days'),
    dcc.Dropdown(
        id='days',
        options= [{'label': k, 'value':k} for k in all_days],
        value = None,
        multi=True),
    dcc.Graph(id="graph")
])

defplot_tips(data=tips, days=None):
    if days isnotNone:
        data=data[data.day.isin(days)]
        fig = px.scatter(data, x='total_bill', y='tip', color='day')
    else:
        data=data[data.day.isin(all_days)]
        fig = px.scatter(data, x='total_bill', y='tip', color='day')
    return (fig)

@app.callback(
    dash.dependencies.Output('graph', "figure"),
    [dash.dependencies.Input('days', 'value') ] )defmake_figure(days):
    fig = plot_tips(data = tips, days= days)
    return (fig)

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

Please note that colours are assigned dynamically and are not consistent so e.g. Thursday is green if all colours are shown but becomes blue when selected on its own. This is not intuitive and could be improved.

Post a Comment for "Unable To Show Graph When Dropdown List Is Cleared In Dash Plotly"