Getting <script> and <div> tags from Plotly using Python

With Plotly 4, use plotly.io.to_html:

import plotly

# Returns a `<div>` and `<script>`
plotly.io.to_html(figure, include_plotlyjs=False, full_html=False)

# Returns a full standalone HTML
plotly.io.to_html(figure)

Reference: https://plotly.com/python-api-reference/generated/plotly.io.to_html.html


If you call:

plotly.offline.plot(data, filename='file.html')

It creates a file named file.html and opens it up in your web browser. However, if you do:

plotly.offline.plot(data, include_plotlyjs=False, output_type='div')

the call will return a string with only the div required to create the chart, which you can store in whatever variable you desire (and not to disk).

I just tried it and it returned, for a given chart that I was doing:

<div id="82072c0d-ba8d-4e86-b000-0892be065ca8" style="height: 100%; width: 100%;" class="plotly-graph-div"></div>
<script type="text/javascript">window.PLOTLYENV=window.PLOTLYENV || {};window.PLOTLYENV.BASE_URL="https://plot.ly";Plotly.newPlot("82072c0d-ba8d-4e86-b000-0892be065ca8", 
[{"y": ..bunch of data..., "x": ..lots of data.., {"showlegend": true, "title": "the title", "xaxis": {"zeroline": true, "showline": true}, 
"yaxis": {"zeroline": true, "showline": true, "range": [0, 22.63852380952382]}}, {"linkText": "Export to plot.ly", "showLink": true})</script>

Notice how its just a tiny portion of an html that you are supposed to embed in a bigger page. For that I use a standard template engine like Jinga2.

With this you can create one html page with several charts arranged the way you want, and even return it as a server response to an ajax call, pretty sweet.

Update:

Remember that you'll need to include the plotly js file for all these charts to work.

You could include <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> just before putting the div you got. If you put this js at the bottom of the page, the charts won't work.