'I have plotly dash app, and get this error: Cannot read properties of null (reading 'layout')

I have web app in plotly dash. I have 3 dropdown and graph with selected item. When I change category i have error:

Cannot read properties of null (reading 'layout').

This is the stacktrace:

(This error originated from the built-in JavaScript code that runs Dash apps. Click to see the full stack trace or open your browser's console.)
TypeError: Cannot read properties of null (reading 'layout')

at u.value (http://127.0.0.1:8050/_dash-component-suites/dash/dcc/async-graph.js:1:7849)

at u.value (http://127.0.0.1:8050/_dash-component-suites/dash/dcc/async-graph.js:1:12619)

at callComponentWillReceiveProps (http://127.0.0.1:8050/_dash-component-suites/dash/deps/[email protected]_0_0m1642415665.14.0.js:13111:16)

at updateClassInstance (http://127.0.0.1:8050/_dash-component-suites/dash/deps/[email protected]_0_0m1642415665.14.0.js:13313:9)

at updateClassComponent (http://127.0.0.1:8050/_dash-component-suites/dash/deps/[email protected]_0_0m1642415665.14.0.js:17242:22)

at beginWork (http://127.0.0.1:8050/_dash-component-suites/dash/deps/[email protected]_0_0m1642415665.14.0.js:18755:18)

at HTMLUnknownElement.callCallback (http://127.0.0.1:8050/_dash-component-suites/dash/deps/[email protected]_0_0m1642415665.14.0.js:182:16)

at Object.invokeGuardedCallbackDev (http://127.0.0.1:8050/_dash-component-suites/dash/deps/[email protected]_0_0m1642415665.14.0.js:231:18)

at invokeGuardedCallback (http://127.0.0.1:8050/_dash-component-suites/dash/deps/[email protected]_0_0m1642415665.14.0.js:286:33)

at beginWork$1 (http://127.0.0.1:8050/_dash-component-suites/dash/deps/[email protected]_0_0m1642415665.14.0.js:23338:9)

The relevant code is the following:

app.layout = html.Div([

    html.Div([
        html.Div([
            html.Div([
                html.H3('Spark Visual app', style={"margin-bottom": "0px", 'color': 'white'}),

            ]),
        ], className="six column", id="title")

    ], id="header", className="row flex-display", style={"margin-bottom": "25px"}),

    html.Div([
        html.Div([
            dcc.Graph(id='map_1',
                      config={'displayModeBar': 'hover'}),

        ], className="create_container 12 columns"),

    ], className="row flex-display"),

    html.Div([
        html.Div([
            html.P('Izaberi kategoriju:', className='fix_label', style={'color': 'white'}),
            dcc.Dropdown(id='w_countries',
                         multi=False,
                         clearable=True,
                         disabled=False,
                         style={'display': True},
                         value='Economy',
                         placeholder='Select category',
                         options=[{'label': c, 'value': c}
                                  for c in region], className='dcc_compon'),

            html.P('Izaberi podkategoriju:', className='fix_label', style={'color': 'white'}),
            dcc.Dropdown(id='w_countries1',
                         multi=False,
                         clearable=True,
                         disabled=False,
                         style={'display': True},
                         placeholder='Select subcategory',
                         options=[], className='dcc_compon'),

            html.P('Izaberi zemlju:', className='fix_label', style={'color': 'white'}),
            dcc.Dropdown(id='w_countries2',
                         multi=True,
                         clearable=True,
                         disabled=False,
                         style={'display': True},
                         value=['European Union', 'Belgium'],
                         placeholder='Select country',
                         options=[{'label': c, 'value': c}
                                  for c in countries], className='dcc_compon'),

            html.P('Izaberi godinu:', className='fix_label', style={'color': 'white', 'margin-left': '1%'}),
            dcc.RangeSlider(id='select_years',
                            min=2019,
                            max=2021,
                            dots=False,
                            value=[2020, 2021]),

        ], className="create_container three columns"),

        html.Div([

            dcc.Graph(id='bar_line_1', figure={}, clickData=None, hoverData=None,
                      # I assigned None for tutorial purposes. By defualt, these are None, unless you specify otherwise.
                      config={
                          'staticPlot': False,  # True, False
                          'scrollZoom': True,  # True, False
                          'doubleClick': 'reset',  # 'reset', 'autosize' or 'reset+autosize', False
                          'showTips': False,  # True, False
                          'displayModeBar': True,  # True, False, 'hover'
                          'watermark': True,
                          # 'modeBarButtonsToRemove': ['pan2d','select2d'],
                      })
        ]),

        html.Div([
            dcc.Graph(id='pie',
                      config={'displayModeBar': 'hover'}),

        ], className="create_container three columns"),

    ], className="row flex-display"),

], id="mainContainer", style={"display": "flex", "flex-direction": "column"})

# Create line  chart
@app.callback(Output('bar_line_1', 'figure'),
              [Input('w_countries', 'value')],
              [Input('w_countries1', 'value')],
              [Input('w_countries2', 'value')])
def update_graph(w_countries, w_countries1, country_chosen):
    # Data for line

    mon = np.array(terr2)
    mon1 = mon[5][1]


    coun = []
    coun = np.array(country_chosen)
    #
    # ECONOMY INFLATION
    #
    wctr1 = w_countries1
    if (w_countries == 'Economy') & (w_countries1 == 'Inflation - annual growth rate'):
        valueEu1 = []
        if ('European Union' in coun):
            valueEu1 = getArr('European Union')

        valueMal1 = []
        if ('Malta' in coun):
            valueMal1 = getArr('Malta')

        valueSer1 = []
        if ('Serbia' in coun):
            valueSer1 = getArr('Serbia')

        valueEa1 = []
        if ('Euro area' in coun):
            valueEa1 = getArr('Euro area')

        valueBel1 = []
        if ('Belgium' in coun):
            valueBel1 = getArr('Belgium')

        return {
            'data': [go.Scatter(x=lab,
                                y=valueEu1,
                                mode='lines+markers',
                                name='European Union',
                                line=dict(shape="spline", smoothing=1.3, width=3, color='#E6D1D1'),
                                marker=dict(size=5, symbol='circle', color='lightblue',
                                            line=dict(color='#E6D1D1', width=2)
                                            ),
                                hoverinfo='text',
                                hovertext=
                                '<b>Country</b>: ' + 'European Union' + '<br>'

                                ),

                     go.Scatter(x=lab,
                                y=valueBel1,
                                mode='lines+markers',
                                name='Belgium',
                                line=dict(shape="spline", smoothing=1.3, width=3, color='#FF00FF'),
                                marker=dict(size=5, symbol='circle', color='lightblue',
                                            line=dict(color='#FF00FF', width=2)
                                            ),
                                hoverinfo='text',
                                hovertext=
                                '<b>Country</b>: ' + 'Belgium' + '<br>'

                                ),
                     go.Scatter(x=lab,
                                y=valueSer1,
                                mode='lines+markers',
                                name='Serbia',
                                line=dict(shape="spline", smoothing=1.3, width=3, color='#FF0000'),
                                marker=dict(size=5, symbol='circle', color='lightblue',
                                            line=dict(color='#FF0000', width=2)
                                            ),
                                hoverinfo='text',
                                hovertext=
                                '<b>Country</b>: ' + 'Serbia' + '<br>'
                                )
                     ],

            'layout': go.Layout(
                barmode='stack',
                plot_bgcolor='#808080',
                paper_bgcolor='#A8A8A8',
                title={
                    'text': 'Inflation - annual growth rate' + '  ' + '<br>' +
                            "(change compared with same month of previous year)" + '</br>',

                    'y': 0.93,
                    'x': 0.5,
                    'xanchor': 'center',
                    'yanchor': 'top'},
                titlefont={
                    'color': 'white',
                    'size': 20},

                hovermode='closest',
                showlegend=True,

                xaxis=dict(title='<b>Year</b>',
                           spikemode='toaxis+across',
                           spikedash='solid',
                           tick0=0,
                           dtick=1,
                           color='white',
                           showline=True,
                           showgrid=True,
                           showticklabels=True,
                           linecolor='white',
                           linewidth=2,
                           ticks='outside',
                           tickfont=dict(
                               family='Arial',
                               size=12,
                               color='white'
                           )

                           ),

                yaxis=dict(title='<b>%</b>',
                           color='white',
                           showline=True,
                           showgrid=True,
                           showticklabels=True,
                           linecolor='white',
                           linewidth=2,
                           ticks='outside',
                           tickfont=dict(
                               family='Arial',
                               size=12,
                               color='white'
                           )

                           ),

                legend={
                    'orientation': 'h',
                    'bgcolor': '#010915',
                    'xanchor': 'center', 'x': 0.5, 'y': -0.3},
                font=dict(
                    family="sans-serif",
                    size=12,
                    color='white'),

            )

        }
    #
    # ECONOMY INFLATION
    
    # Strart Economy-Monthly production in construction
    #
    elif (w_countries == 'Economy') and (w_countries1 == 'Monthly production in construction'):

        valueEu1 = []
        if ('European Union' in coun):
            valueEu1 = getMPIC('European Union')

        valueMal1 = []
        if ('Malta' in coun):
            valueMal1 = getMPIC('Malta')

        # valueSer1=[]
        # if ('Serbia' in coun):
        #    valueSer1=getMPIC('Serbia')

        valueEa1 = []
        if ('Euro area' in coun):
            valueEa1 = getMPIC('Euro area')

        valueBel1 = []
        if ('Belgium' in coun):
            valueBel1 = getMPIC('Belgium')

        return {
            'data': [go.Scatter(x=lab,
                                y=valueEu1,
                                mode='lines+markers',
                                name='European Union',
                                line=dict(shape="spline", smoothing=1.3, width=3, color='#E6D1D1'),
                                marker=dict(size=5, symbol='circle', color='lightblue',
                                            line=dict(color='#E6D1D1', width=2)
                                            ),
                                hoverinfo='text',
                                hovertext=
                                '<b>Country</b>: ' + 'European Union' + '<br>'
                                ),
                     go.Scatter(x=lab,
                                y=valueBel1,
                                mode='lines+markers',
                                name='Belgium',
                                line=dict(shape="spline", smoothing=1.3, width=3, color='#FF0000'),
                                marker=dict(size=5, symbol='circle', color='lightblue',
                                            line=dict(color='#FF0000', width=2)
                                            ),
                                hoverinfo='text',
                                hovertext=
                                '<b>Country</b>: ' + 'Belgium' + '<br>'
                                )
                     ],

            'layout': go.Layout(
                barmode='stack',
                plot_bgcolor='#808080',
                paper_bgcolor='#A8A8A8',
                title={
                    'text': 'Monthly production in construction' + '  ' + '<br>' +
                            "(Index 2015=100)" + '</br>',

                    'y': 0.93,
                    'x': 0.5,
                    'xanchor': 'center',
                    'yanchor': 'top'},
                titlefont={
                    'color': 'white',
                    'size': 20},

                hovermode='closest',
                showlegend=True,

                xaxis=dict(title='<b>Year</b>',
                           spikemode='toaxis+across',
                           spikedash='solid',
                           tick0=0,
                           dtick=1,
                           color='white',
                           showline=True,
                           showgrid=True,
                           showticklabels=True,
                           linecolor='white',
                           linewidth=2,
                           ticks='outside',
                           tickfont=dict(
                               family='Arial',
                               size=12,
                               color='white'
                           )

                           ),

                yaxis=dict(title='<b>Index 2015=100</b>',
                           color='white',
                           showline=True,
                           showgrid=True,
                           showticklabels=True,
                           linecolor='white',
                           linewidth=2,
                           ticks='outside',
                           tickfont=dict(
                               family='Arial',
                               size=12,
                               color='white'
                           )

                           ),

                legend={
                    'orientation': 'h',
                    'bgcolor': '#010915',
                    'xanchor': 'center', 'x': 0.5, 'y': -0.3},
                font=dict(
                    family="sans-serif",
                    size=12,
                    color='white'),

            )

        }


    #
    # END Economy-Monthly production in construction
    #
    # END of ECONOMY
    #
    #
    # Start POPULATION AND HEALTH
    #
    #
    # POPULATION AND HEALTH-Monthly excess mortality
    #
    elif (w_countries == 'Population and health') & (w_countries1 == 'Monthly excess mortality'):

        # valueMal1=[]
        # if ('Malta' in coun):
        #   valueMal1=getPAHMEM('Malta')

        # valueSer1=[]
        # if ('Serbia' in coun):
        #    valueSer1=getMPIC('Serbia')

        # valueEa1=[]
        # if ('Euro area' in coun):
        #   valueEa1=getPAHMEM('Euro area')
        valueEu1 = []
        if ('European Union' in coun):
            valueEu1 = getPAHMEM('European Union')

        valueBel1 = []
        if ('Belgium' in coun):
            valueBel1 = getPAHMEM('Belgium')

        return {
            'data': [go.Scatter(x=labPAHMEM,
                                y=valueEu1,
                                mode='lines+markers',
                                name='European Union',
                                line=dict(shape="spline", smoothing=1.3, width=3, color='#E6D1D1'),
                                marker=dict(size=5, symbol='circle', color='lightblue',
                                            line=dict(color='#E6D1D1', width=2)
                                            ),
                                hoverinfo='text',
                                hovertext=
                                '<b>Country</b>: ' + 'European Union' + '<br>'
                                ),
                     go.Scatter(x=labPAHMEM,
                                y=valueBel1,
                                mode='lines+markers',
                                name='Belgium',
                                line=dict(shape="spline", smoothing=1.3, width=3, color='#FF0000'),
                                marker=dict(size=5, symbol='circle', color='lightblue',
                                            line=dict(color='#FF0000', width=2)
                                            ),
                                hoverinfo='text',
                                hovertext=
                                '<b>Country</b>: ' + 'Belgium' + '<br>'
                                )
                     ],

            'layout': go.Layout(
                barmode='stack',
                plot_bgcolor='#808080',
                paper_bgcolor='#A8A8A8',
                title={
                    'text': 'Monthly excess mortality' + '  ' + '<br>' +
                            "(% of additional deaths compared with average monthly deaths in 2016-2019)" + '</br>',

                    'y': 0.93,
                    'x': 0.5,
                    'xanchor': 'center',
                    'yanchor': 'top'},
                titlefont={
                    'color': 'white',
                    'size': 20},

                hovermode='closest',
                showlegend=True,

                xaxis=dict(title='<b>Year</b>',
                           spikemode='toaxis+across',
                           spikedash='solid',
                           tick0=0,
                           dtick=1,
                           color='white',
                           showline=True,
                           showgrid=True,
                           showticklabels=True,
                           linecolor='white',
                           linewidth=2,
                           ticks='outside',
                           tickfont=dict(
                               family='Arial',
                               size=12,
                               color='white'
                           )

                           ),

                yaxis=dict(title='<b>% of additional deaths</b>',
                           color='white',
                           showline=True,
                           showgrid=True,
                           showticklabels=True,
                           linecolor='white',
                           linewidth=2,
                           ticks='outside',
                           tickfont=dict(
                               family='Arial',
                               size=12,
                               color='white'
                           )

                           ),

                legend={
                    'orientation': 'h',
                    'bgcolor': '#010915',
                    'xanchor': 'center', 'x': 0.5, 'y': -0.3},
                font=dict(
                    family="sans-serif",
                    size=12,
                    color='white'),

            )

        }


    #
    # END POPULATION AND HEALTH-Monthly excess mortality
    elif (w_countries == 'Population and health') &  (w_countries1 == 'Number of deaths by week'):

            valueEu1 = []
            if ('European Union' in coun):
                valueEu1 = getPAHDBW('European Union')

            valueBel1 = []
            if ('Belgium' in coun):
                valueBel1 = getPAHDBW('Belgium')

            labelDbw = getLabelPAHDBW2()
            return {
                'data': [go.Scatter(x=labelDbw,
                                    y=valueEu1,
                                    mode='lines+markers',
                                    name='European Union',
                                    line=dict(shape="spline", smoothing=1.3, width=3, color='#E6D1D1'),
                                    marker=dict(size=5, symbol='circle', color='lightblue',
                                                line=dict(color='#E6D1D1', width=2)
                                                ),
                                    hoverinfo='text',
                                    hovertext=
                                    '<b>Country</b>: ' + 'European Union' + '<br>'
                                    ),
                         go.Scatter(x=labPAHMEM,
                                    y=valueBel1,
                                    mode='lines+markers',
                                    name='Belgium',
                                    line=dict(shape="spline", smoothing=1.3, width=3, color='#FF0000'),
                                    marker=dict(size=5, symbol='circle', color='lightblue',
                                                line=dict(color='#FF0000', width=2)
                                                ),
                                    hoverinfo='text',
                                    hovertext=
                                    '<b>Country</b>: ' + 'Belgium' + '<br>'
                                    )
                         ],

                'layout': go.Layout(
                    barmode='stack',
                    plot_bgcolor='#808080',
                    paper_bgcolor='#A8A8A8',
                    title={
                        'text': 'Number of deaths by week' + '  ' + '<br>' +
                                "(absolute numbers)" + '</br>',

                        'y': 0.93,
                        'x': 0.5,
                        'xanchor': 'center',
                        'yanchor': 'top'},
                    titlefont={
                        'color': 'white',
                        'size': 20},

                    hovermode='closest',
                    showlegend=True,

                    xaxis=dict(title='<b>Year</b>',
                               spikemode='toaxis+across',
                               spikedash='solid',
                               tick0=0,
                               dtick=1,
                               color='white',
                               showline=True,
                               showgrid=True,
                               showticklabels=True,
                               linecolor='white',
                               linewidth=2,
                               ticks='outside',
                               tickfont=dict(
                                   family='Arial',
                                   size=12,
                                   color='white'
                               )

                               ),

                    yaxis=dict(title='<b>% of additional deaths</b>',
                               color='white',
                               showline=True,
                               showgrid=True,
                               showticklabels=True,
                               linecolor='white',
                               linewidth=2,
                               ticks='outside',
                               tickfont=dict(
                                   family='Arial',
                                   size=12,
                                   color='white'
                               )

                               ),

                    legend={
                        'orientation': 'h',
                        'bgcolor': '#010915',
                        'xanchor': 'center', 'x': 0.5, 'y': -0.3},
                    font=dict(
                        family="sans-serif",
                        size=12,
                        color='white'),

                )

            }

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


Solution 1:[1]

This error message appears when the figure property of the dcc.Graph component is None. If all of your conditional statements (if/elif) evaluate to False, then your callback will return None. This could be the cause of your error message.

If you just want an empty graph when all conditions evaluate to false, then add the following to the end of your callback:

else:
    return {}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 3.14 Thon