Bertrand
Bertrand

Reputation: 113

How to display html file with Dash HTML components

I plotted a figure that I saved in fig.html and I would like to display it with dash-html-components.

Which Dash HTML component should I use and what is the exact syntax? I have tried several components from the dash list but I think I am not using it the right way.

this is my current result:

enter image description here

Here is an example of what I tried:

import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash(__name__, external_stylesheets=['../app/css/template.css'])

app.title = 'Test Dashboard'

app.layout = html.Div([
    html.H1(
      children='Test Dashboard',
      style={
         'textAlign': 'center'
      }
    ),

    html.Br(),

    html.Iframe(src='fig.html')

],
style={'width': '75%',
          'textAlign': 'center',
          'margin-left':'12.5%',
          'margin-right':'0'
         }
)

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

Upvotes: 2

Views: 12731

Answers (2)

emher
emher

Reputation: 6024

Since figures in Dash are essentially dictionaries, which are serialized to JSON and passed to plotly.js for rendering (for details, see the documentation), i would consider JSON as the preferred format for saving the figure. Here is a small example app (requires Dash 0.0.12),

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

cache = "fig.json"
# Construct a figure object and save it as json.
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length")
with open(cache, 'w') as f:
    f.write(fig.to_json())
# Create example app.
app = dash.Dash(prevent_initial_callbacks=True)
app.layout = html.Div([dcc.Graph(id="graph"), html.Button("Click me", id="btn")])


@app.callback(Output("graph", "figure"), [Input("btn", "n_clicks")])
def func(n_clicks):
    with open(cache, 'r') as f:
        return json.load(f)


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

Compared to pickle, JSON also has the advantage of being human readable, and you avoid the pickle.load statement, which can potentially introduce security vulnerabilities. For an extended discussion of pickle vs JSON, see this question.

Upvotes: 4

Bertrand
Bertrand

Reputation: 113

I finaly saved my graph with pickle:

import pickle

filename = 'graph.pkl'
with open(filename, 'wb') as f:
    pickle.dump(fig, f)

and then load it where I need it:

import dash_core_components as dcc
import dash_html_components as html
import pickle

filename = 'graph.pkl'
with open(filename, 'rb') as f:
    fig = pickle.load(f)

html.Div([dcc.Graph(figure=fig)])

But I am still interested to know if this is a good way to do it or not.

Upvotes: 2

Related Questions