python - 如何使用 Dash HTML 组件显示 html 文件

标签 python html plotly-dash

我绘制了一个保存在 fig.html 中的图形,我想用 dash-html-components 显示它。

我应该使用哪个 Dash HTML 组件,确切的语法是什么?我已经尝试了破折号列表中的几个组件,但我认为我没有以正确的方式使用它。

这是我目前的结果:

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)

最佳答案

由于 Dash 中的图形本质上是字典,它们被序列化为 JSON 并传递给 plotly.js 进行渲染(有关详细信息,请参阅 documentation ),我认为 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 的扩展讨论,请参阅 this question .

关于python - 如何使用 Dash HTML 组件显示 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61975627/

相关文章:

python - 阴谋冲刺 : Render a Graph only if certain data in a Pandas DataFrame exists

python - 如何使用 Plotly 创建垂直滚动条?

python - 需要为 Python 3.5.1 安装 urllib2

python - tasklist 没有列出 64 位系统中的所有模块

Python 2.7 多处理障碍

html - 指南针 Sprite 进阶

html - Css 边框为 :hover element

html - 我如何将所有元素居中?

plotly - 在破折号中调整图形大小

Python函数指针