Dash app does not load plots on Windows 10

Dash app is not loading on Windows 10. Also, it sometimes works and sometimes doesn’t on MacOs.

HI @mandana welcome to the forums!

Could you add some information? It’s almost impossible to help you with the information provided.

Sure, I thought maybe it’s a general problem :smiley:
What kind of information will be useful?

 * Serving Flask app 'dash_app'
 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:8050
Press CTRL+C to quit

This is how it loads:


Dash is running on http://127.0.0.1:8050/

This is how it should load:

The first thing I would do is running the app in debug=True

debug=True makes it worse.

:rofl:

Do you get error messages?

Nope, nothing. sometimes after refreshing several times it randomly loads.

Can you show us your code?

from dash import Dash, MATCH
from dash import dcc
from dash import html
from dash.dependencies import Output, Input
import pandas as pd 
import plotly.express as px
import plotly.graph_objs as go
import numpy as np
from sklearn.metrics import mean_squared_error, mean_absolute_error, mean_absolute_percentage_error
from datetime import date
import json 

model_names = ["CNN", "GRU", "LSTM", "MLP" ]
attribute_names = ["MLP", "LSTM", "CNN_LSTM", "GRU" ]
csv_files = {"Big Dataset":"big_data_forecast",
             "Small Dataset": "small_data_forecast"
             }

datasets = ["Big Dataset", "Small Dataset"]
active_dataset = "Big Dataset"
ds = {}
for i in datasets:
  ds[i] = pd.read_csv("./{}".format(csv_files[i]))

class acc_error: 
  def __init__(self, acc, id):
    self.id = id 
    self.visible = True
    self.MLP = model_error_metrics(acc, "MLP")
    self.LSTM = model_error_metrics(acc, "LSTM")
    self.CNN = model_error_metrics(acc, "CNN")
    self.GRU = model_error_metrics(acc, "GRU")
    
class model_error_metrics:
  def __init__(self, acc, model_name):
    self.visible = False
    self.rmse = np.sqrt(mean_squared_error(acc["Actual value"],acc[model_name]))
    self.mae = mean_absolute_error(acc["Actual value"], acc[model_name])
    self.mape = mean_absolute_percentage_error(acc["Actual value"], acc[model_name]) 
    self.wmape = np.abs(acc["Actual value"] - acc[model_name]).sum() / np.abs(acc["Actual value"] ).sum()

def plot_forecast(acc, id):
  model_forecasts = []
  model_forecasts.append(go.Scatter(x=acc["Date"], y=acc["Actual value"], name=("Actual Amount")))
  for model_name in model_names:
    model_forecasts.append(go.Scatter(x=acc["Date"], y=acc[model_name], name=("%s" % model_name), visible='legendonly'))

  layout = go.Layout(title="Forecasts on GL Account %s" %id, xaxis = dict(title="Date"), yaxis=dict(title="Transaction Amount (USD)"))
  fig = go.Figure(data=model_forecasts, layout=layout)
  return fig

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

app = Dash(__name__, external_stylesheets=external_stylesheets)
errors = [acc_error(ds["Big Dataset"], "Big Dataset"), acc_error(ds["Small Dataset"], "Small Dataset")]

model_dict = {0 : "ACTUAL",
    1: "CNN",
    2: "GRU",
    3: "LSTM",
    4: "MLP",
  }

def div_graph(id):
    data = ds[id]
    fig = plot_forecast(data, id)
    return html.Div(
      className = "row",
      children = [
        html.Div([
          dcc.Graph(id={"type": "forecast_graph", "index": id}, figure = fig, className = "eight columns"),
        ]),
        html.Div(id ={"type": "error_metrics", "index": id}, children="", className = "four columns"),
      ]
   )

app.layout = html.Div([
  html.Div([
    html.Div([
        dcc.RadioItems(datasets, active_dataset, id = "dataset", inline=True),
    ], className='eight columns'),
  ], className='row'),
  html.Div(className="row", id = "graphs",
    children=[
      div_graph(active_dataset),
    ])
]) 

@app.callback(
    Output(f'graphs','children'),
    Input('dataset','value')
)
def update_graph(dataset):
  global active_dataset
  global ds
  if dataset != active_dataset: 
    active_dataset = dataset
    return [div_graph(active_dataset)]

@app.callback(
    Output({"type" : "error_metrics", "index" : MATCH}, 'children'),
    Input({"type" : "forecast_graph", "index" : MATCH}, 'id'),
    [Input({"type" : "forecast_graph", "index" : MATCH}, 'restyleData')],
    )
def update_error(id, restyleData):
    legend_info = json.loads(json.dumps(restyleData, indent=2))
    id = id["index"]

    dataset = errors[0]
    for i in errors: 
      if i.id == id: 
        dataset = i
        break

    print(legend_info)
    if legend_info != None:    
      model_name = model_dict[legend_info[1][0]]
      visibility = legend_info[0]["visible"][0] == True
      m = getattr(dataset, model_name)
      m.visible = visibility
      setattr(dataset, model_name, m)

    results = []
    for model in model_names: 
      m = getattr(dataset, model)
      if m.visible == True: 
        results += [
          html.H5(f"{model} Model Error:"),
          html.Div(f"RMSE: {m.rmse}"),
          html.Div(f"MAE: {m.mae}"),
          html.Div(f"MAPE: {m.mape}"),
          html.Div(f"WMAPE: {m.wmape}"),
          html.Br()
        ]
    return results 

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

Sorry can I have a question that you just want to return graph based on Radio Items right? When you choosing Big Dataset or Small Dataset, graph based on it will be showed.
Because I don’t fully understand your code.

Yes, that’s right.

1 Like

Not sure why but i think you can simplify your code like this and i think it will work:

from dash import Dash, dcc, html, dcc, Input, Output
from dash.exceptions import PreventUpdate
import pandas as pd
import dash_bootstrap_components as dbc
import pandas as pd
import plotly.express as px

df = px.data.gapminder().query("country==['Canada']")
df2 = px.data.gapminder().query("country==['Afghanistan']")

app = Dash(__name__, external_stylesheets=[dbc.themes.LUX])
app.layout = html.Div([
    dbc.Row([
        dbc.Col([
            dbc.RadioItems(id='my-radioitems', 
                           options=[{'label':'big_dataset', 'value':'big_dataset'},
                                    {'label':'small_dataset', 'value':'small_dataset'}],
                           value='small_dataset',inline=True),
            dcc.Graph(id='my-line-graph', figure={}),
        ])
    ])
])


@app.callback(Output('my-line-graph', 'figure'),
             Input('my-radioitems','value'))

def update_line_graph(my_radioitems):
    if my_radioitems == 'big_dataset':
        fig = px.line(df, x="year", y='lifeExp')
        return fig
    else:
        fig = px.line(df2, x="year", y='lifeExp')
        return fig
if __name__ == "__main__":
    app.run_server(debug=False)