Как сохранить макет Dash в файл HTML

Я пытаюсь сохранить макет Dash в HTML-файле, но не могу найти способ сделать это. Как ни странно, достаточно легко сохранить одну фигуру Plotly, но не макет Dash. у кого-нибудь есть решение?

Я видел, что на этот вопрос уже есть ответ здесь https://stackoverflow.com/a/51013594/3057377, но я не не понимаю. Особенно заметка о потере интерактивности. Видно, что интерактивность сохраняется при сохранении одного сюжета, поэтому она должна быть одинаковой для всего макета.

Вот что я уже пробовал:

import dash_core_components as dcc
import dash_html_components as html
import dash
import plotly as py
import plotly.graph_objs as go

# Create two figures.
fig1 = go.Figure(data=go.Scatter(x=[0, 1, 2], y=[0, 10, 0]))
fig2 = go.Figure(data=go.Scatter(x=[0, 1, 2], y=[0, -10, 0]))

# Write fig1 to HTML. The three methods below work.
py.io.write_html(fig1, file="fig1_a.html", auto_open=True)
fig1.write_html(file="fig1_b.html", auto_open=True)
py.offline.plot(fig1, filename='fig1_c.html', auto_open=True)

# Write fig2 to HTML. The three methods below work.
py.io.write_html(fig2, file="fig2_a.html", auto_open=True)
fig2.write_html(file="fig2_b.html", auto_open=True)
py.offline.plot(fig2, filename='fig2_c.html', auto_open=True)


# Now create a layout that will be displayed in an HTML page.
app = dash.Dash(__name__)
app.layout = html.Div([dcc.Graph(id="fig1", figure=fig1),
                       dcc.Graph(id="fig2", figure=fig2)])

# Trying to save the layout to HTML doesn’t work with the same three methods as above.
print("############  1")
try:
    py.io.write_html(app.layout, file="app_layout_a.html", auto_open=True)
except Exception as e:
    print(e)

print("############  2")
try:
    app.layout.write_html(file="app_layout_c.html", auto_open=True)
except Exception as e:
    print(e)

print("############  3")
try:
    py.offline.plot(app.layout, filename='app_layout_b.html')
except Exception as e:
    print(e)

# But the layout displays correctly when served by Dash.
app.run_server(debug=True)


person nico    schedule 09.02.2020    source источник


Ответы (2)


Просто используйте следующую команду:

fig.write_html("path/to/file.html")
person Hatem Elattar    schedule 10.12.2020

Вы можете сохранить HTML-код, содержащий информацию о графике, в переменную. Чтобы построить график, вы можете использовать html.Iframe из dash_html_components. Если график генерируется внутри обратного вызова Dash, вы можете вернуть эту переменную или iframe в качестве вывода обратного вызова.

Я также делюсь тем, как я сохраняю графические фигуры в HTML. Сюжет остается интерактивным, а файл HTML значительно легче, чем другие альтернативы (например, fig.write_html()).

with open('plot.html', 'w') as f:
    f.write(fig.to_html(full_html=False, include_plotlyjs='cdn'))

Вот минимальный рабочий пример в приложении Dash. В этом случае фигура находится в обратном вызове, потому что каждый раз, когда вы нажимаете внизу Rotate, фигура обновляется и поворачивает метки галочки. Это приложение является модификацией Plotly Docs:

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

df = px.data.tips()

app = dash.Dash(__name__)

app.layout = html.Div([
    html.Button("Rotate", id='button', n_clicks=0), 
    html.Div(id="output", children=[])
])

@app.callback(
    Output('output', 'children'), # The output will be displayed in  html.Div(id="output)
    [Input("button", "n_clicks")])
def rotate_figure(n_clicks):
    fig = px.histogram(df, x="sex", height=500)
    fig.update_xaxes(tickangle=n_clicks*45)

    # The plotly figure is saved as HTML in a variable
    html_data = fig.to_html(full_html=False, include_plotlyjs='cdn')
    
    # The variable is then displayed as a plot using Iframe from dash_html_components
    html_plot = html.Iframe(srcDoc = html_data, 
                            style = {"height": "1000px", 
                                     "width": "1000px",
                                     "display":"flex",
                                     "align-items": "center", 
                                     "justify-content":  "center"}
                            )
    
    # Now you can return the Iframe as a children of a Div
    return html_plot

app.run_server(debug=True)



person Álvaro H.G    schedule 05.04.2021