python save plotly plot to local file and insert i

2020-02-07 14:07发布

I am using python and plotly to product interactive html report. This post gives a nice framework.

If I produce the plot(via plotly) online, and insert the url into the html file, it works but refreshing the charts takes a long time. I wonder if I could produce the chart offline and have it embedded in the html report, so that loading speed is not a problem.

I find plot offline would generate a html for the chart, but I don't know how to embed it in another html. Anyone could help?

标签: python plotly
7条回答
女痞
2楼-- · 2020-02-07 14:42

In addition to the other answers, another possible solution is to use to_json() on the plotly figure.

No need for custom JSON serializer or use of internal solutions.

import plotly

# create a simple plot
bar = plotly.graph_objs.Bar(x=['giraffes', 'orangutans', 'monkeys'], 
                            y=[20, 14, 23])
layout = plotly.graph_objs.Layout()
fig = plotly.graph_objs.Figure([bar], layout)

# convert it to JSON
fig_json = fig.to_json()

# a simple HTML template
template = """<html>
<head>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
    <div id='divPlotly'></div>
    <script>
        var plotly_data = {}
        Plotly.react('divPlotly', plotly_data.data, plotly_data.layout);
    </script>
</body>

</html>"""

# write the JSON to the HTML template
with open('new_plot.html', 'w') as f:
    f.write(template.format(fig_json))
查看更多
登录 后发表回答