Dropdown with px.histogram

Hi,
Is using dropdowns with px.histogram possible? I wrote some code using the same format as I have for previous px. plots yet I get an error stating KeyError: None.
Any help would be appreciated.

import dash
import dash_core_components as dcc
import dash_html_components as html
import flask
import plotly.express as px
from dash.dependencies import Input, Output
import pandas as pd

server = flask.Flask(__name__)
app = dash.Dash(__name__, server=server)

df = pd.read_csv('/Users/mythilisutharson/documents/cam_work/mof_explorer_flourish/MOF_trans_data2.csv')
features = df.columns

app.layout = html.Div([
    html.Div([dcc.Graph(id='dist-plot', animate=False)]),
    html.Div([
        html.Label(["Select X variable:",
                    dcc.Dropdown(id='xaxis-dist', options=[{'label': i, 'value': i} for i in features],
                                 multi=False,
                                 placeholder="Select an option for X"
                                 )]),

    ])
])


@app.callback(Output("dist-plot", "figure"), [Input('xaxis-dist', "value"),
                                              ])
def make_figure(x):
    return px.histogram(df, x=df[x], marginal="rug", color="MOF family",
                        animation_frame="Pressure (bar)",
                        hover_data=df.columns, hover_name="DDEC code",
                        ).update_xaxes(showgrid=False, title="Density", autorange=True
                                       ).update_yaxes(title=' ', showgrid=False,
                                                      autorange=True).update_layout(
        clickmode='event+select', hovermode='closest', margin={'l': 50, 'b': 80, 't': 50, 'r': 10}, autosize=True
    ).update_traces(marker=dict(opacity=0.7, line=dict(width=0.5, color='DarkSlateGrey'),
                                ))


app.run_server(debug=True)

The data used is the following:


Thank you!

Hi @msuths1, do you get this KeyError only when the app is launching? I believe the problem comes from when the app is launchedm then the value of the dropdown is None, hence the error. A common workaround patter is to return dash.no_update when the Input is None:

@app.callback(Output("dist-plot", "figure"), [Input('xaxis-dist', "value"),
                                              ])
def make_figure(x):
    if x is None:
        return dash.no_update
    return px.histogram(df, x=df[x], marginal="rug", color="MOF family",
                        animation_frame="Pressure (bar)",
                        hover_data=df.columns, hover_name="DDEC code",
                        ).update_xaxes(showgrid=False, title="Density", autorange=True
                                       ).update_yaxes(title=' ', showgrid=False,
                                                      autorange=True).update_layout(
        clickmode='event+select', hovermode='closest', margin={'l': 50, 'b': 80, 't': 50, 'r': 10}, autosize=True
    ).update_traces(marker=dict(opacity=0.7, line=dict(width=0.5, color='DarkSlateGrey'),
                                ))

(not tested, hope there are no typos :-))

1 Like

Yes it was only when the app is launching. Thank you so much! That worked perfectly.

Hi @Emmanuelle
Hope you are well.
I tried what you suggested for the px.Scatter_3D when uploading a document to plot a 3D plot. This exact code works with 2D px.Scatter but not px.Scatter_3D. Could you provide some guidance into why that may be the case. I get the error: ‘NoneType’ object has no attribute ‘split’

import base64
import io
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.express as px
import flask

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
server = flask.Flask(__name__)
app = dash.Dash(__name__, external_stylesheets=external_stylesheets, server=server)

app.layout = html.Div([
    html.Div([dcc.Upload(
        id='data-table-upload',
        children=html.Div(['Drag and Drop or ',
                           html.A('Select Files')
                           ]),
        style={
            'width': '70%',
            'height': '60px',
            'lineHeight': '60px',
            'borderWidth': '1px',
            'borderStyle': 'dashed',
            'borderRadius': '5px',
            'textAlign': 'center',
            'margin': '10px 15%'
        },
        multiple=False
    ),
    ]),
    html.Div([dcc.Graph(id='my-graph')], style={'display': 'inline-block', 'width': '70%', 'height': '75%'}),

    html.Div([
        html.Div([html.Label(["Select X variable:",
                              dcc.Dropdown(id='xaxis-3D', multi=False, placeholder="Select an option for X")],
                             className="six columns"
                             )], style={'width': '170%', 'display': 'inline-block'}),
        html.Div([html.Label(["Select Y variable:",
                              dcc.Dropdown(id='yaxis-3D', multi=False, placeholder='Select an option for Y')],
                             className="six columns"
                             ), ], style={'width': '170%', 'display': 'inline-block'}),
        html.Div([html.Label(["Select Z variable:",
                              dcc.Dropdown(id='zaxis-3D', multi=False, placeholder='Select an option for Z')],
                             className="six columns"
                             ), ], style={'width': '170%', 'display': 'inline-block'}),
        html.Div([html.Label(
            ["Select Size variable:",
             dcc.Dropdown(id='saxis-3D', multi=False, placeholder='Select an option for Size')],
            className="six columns"
        )], style={'width': '170%', 'display': 'inline-block'}),
        html.Div([html.Label(
            ["Select Color variable:",
             dcc.Dropdown(id="caxis-3D", multi=False, placeholder='Select an option for Color')],
            className="six columns"
        )], style={'width': '170%', 'display': 'inline-block'})
    ],
        style={'display': 'inline-block', 'width': '23%', })

])


def parse_contents(contents, filename):
    content_type, content_string = contents.split(',')

    decoded = base64.b64decode(content_string)
    try:
        if 'csv' in filename:
            # Assume that the user uploaded a CSV file
            return pd.read_csv(
                io.StringIO(decoded.decode('utf-8')))
        elif 'xls' in filename:
            # Assume that the user uploaded an excel file
            return pd.read_excel(io.BytesIO(decoded))
        elif 'txt' or 'tsv' in filename:
            return pd.read_csv(
                io.StringIO(decoded.decode('utf-8')), delimiter=r'\s+'
            )
    except Exception as e:
        print(e)
        return html.Div([
            'There was an error processing this file.'
        ])


# POPULATE X AXIS DROPDOWN 3D
@app.callback(Output('xaxis-3D', 'options'),
              [Input('data-table-upload', 'contents')],
              [State('data-table-upload', 'filename')])
def populate_xaxis_dropdown(contents, filename):
    df = parse_contents(contents, filename)
    return [{'label': i, 'value': i} for i in df.columns]


# POPULATE Y AXIS DROPDOWN 3D
@app.callback(Output('yaxis-3D', 'options'),
              [Input('data-table-upload', 'contents')],
              [State('data-table-upload', 'filename')])
def populate_yaxis_dropdown(contents, filename):
    df = parse_contents(contents, filename)
    return [{'label': i, 'value': i} for i in df.columns]


# POPULATE Z AXIS DROPDOWN 3D
@app.callback(Output('zaxis-3D', 'options'),
              [Input('data-table-upload', 'contents')],
              [State('data-table-upload', 'filename')])
def populate_zaxis_dropdown(contents, filename):
    df = parse_contents(contents, filename)
    return [{'label': i, 'value': i} for i in df.columns]


# POPULATE C AXIS DROPDOWN 3D
@app.callback(Output('caxis-3D', 'options'),
              [Input('data-table-upload', 'contents')],
              [State('data-table-upload', 'filename')])
def populate_caxis_dropdown(contents, filename):
    df = parse_contents(contents, filename)
    return [{'label': i, 'value': i} for i in df.columns]


# POPULATE S AXIS DROPDOWN 3D
@app.callback(Output('saxis-3D', 'options'),
              [Input('data-table-upload', 'contents')],
              [State('data-table-upload', 'filename')])
def populate_saxis_dropdown(contents, filename):
    df = parse_contents(contents, filename)
    return [{'label': i, 'value': i} for i in df.columns]


@app.callback(Output('my-graph', 'figure'),
              [Input('data-table-upload', 'contents'),
               Input('xaxis-3D', 'value'),
               Input('yaxis-3D', 'value'),
               Input('zaxis-3D', 'value'),
               Input('caxis-3D', 'value'),
               Input('saxis-3D', 'value')],
              [State('data-table-upload', 'filename')]
              )
def make_figure(contents, x, y, z, color, size, filename):
    df = parse_contents(contents, filename)
    if x or y or z or color or size is None:
        return dash.no_update
    return px.scatter_3d(df, x=df[x], y=df[y], z=df[z], title="", animation_frame="Pressure (bar)",
                         animation_group=df.columns[0], size=df[size], color=df[color],
                         hover_name="DDEC code", color_continuous_scale='Viridis',
                         hover_data={}, template="plotly_white",
                         ).update_xaxes(showgrid=False, title=x, autorange=True).update_yaxes(
        showgrid=False, title=y, autorange=True).update_layout(
        clickmode='event+select', hovermode='closest', margin={'l': 50, 'b': 80, 't': 50, 'r': 10}, autosize=True
    ).update_traces(marker=dict(opacity=0.7, showscale=True, line=dict(width=0.5, color='DarkSlateGrey'),
                                colorbar=dict(title=color)))


app.run_server(debug=True)