如何用Dash HTML组件显示html文件

问题描述 投票:0回答:1

我绘制了一个数字,我保存在 阳光 我想用dash-html-components来显示它。

我应该使用哪个Dash HTML组件,准确的语法是什么?我已经尝试了几个dash列表中的组件,但我认为我使用的方式不对。

这是我目前的结果。

enter image description here

下面是我试过的一个例子

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)
python html plotly-dash hyphen
1个回答
1
投票

我最终用pickle保存了我的图表。

import pickle

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

然后在我需要的地方加载它。

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)])

但我还是很想知道这是不是一个好办法。


1
投票

由于Dash中的数字本质上是字典,它被序列化为JSON,并传递给plotly.js进行渲染(详情请参见 文件),我认为JSON是保存数字的首选格式。这里是一个小的示例应用程序(需要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()

与pickle相比,JSON还有一个优势,那就是人类可读性强,而且你避免了 pickle.load 语句,这有可能引入安全漏洞。关于pickle与JSON的详细讨论,请参见 这个问题.

© www.soinside.com 2019 - 2024. All rights reserved.