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

10,184

Solution 1

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.

Solution 2

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

Solution 3

Apologies for the necro-answer really wanted to add a comment to Fermin Silva left behind (https://stackoverflow.com/a/38033016/2805700) - but long standing lurker reputation prevents me.

Anyhow I had a similar need and encoutered an issue with plotly 2.2.2

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

The include_plotlyjs parameter was being ignored when outputting to a div. Based on the comments above, I found a workaround. Basically let plotly plot to file, which does respect the include_plotlyjs parameter. Load into beautiful soup and inject the link to the latest plotly.js on the cdn.

import plotly
import bs4

# return as html fragment
# the include_plotlyjs argument seems to be 
# ignored as it's included regardless when outputting to div
# found an open issue on here - https://github.com/plotly/plotly.py/issues/1043
plotly.offline.plot(
    plot_output, 
    filename = filename,
    config = plot_config,
    include_plotlyjs = False,
    auto_open = False,
)

# load the file
with open(filename) as inf:
    txt = inf.read()
    soup = bs4.BeautifulSoup(txt)

# add in the latest plot-ly js as per https://stackoverflow.com/a/38033016/2805700
js_src = soup.new_tag("script", src="https://cdn.plot.ly/plotly-latest.min.js")
# insert it into the document
soup.head.insert(0, js_src)

# save the file again
with open(filename, "w") as outf:
    outf.write(str(soup))

Cheers

Share:
10,184
HMSCelestia
Author by

HMSCelestia

Electrical Engineering student at GMU who's interest in code extends far beyond the classroom. Currently working to convert previously unused storage space into a small home computer(server)/electronics lab one small step at a time.

Updated on June 12, 2022

Comments

  • HMSCelestia
    HMSCelestia almost 2 years

    I was wondering if anyone knew a good way (preferably a built in method, but I'm open to writing my own of course) to get the <script> and <div> tags from the HTML output of the Plotly offline client.

    I'm already familiar with bokeh and really enjoy using it for 2D visualization, but would really like to integrate Plotly as well for its 3D visualization capabilities.

    Let me know if you need any extra details about the project.

  • Fermin Silva
    Fermin Silva almost 8 years
    The docs start at plot.ly/python , but its very example-based and not super complete. There's also plot.ly/python/offline and a very complete reference: plot.ly/python/reference. Otherwise you might just read the source code: github.com/plotly/plotly.py/blob/master/plotly/offline/…
  • HMSCelestia
    HMSCelestia over 7 years
    Sorry about the confusion earlier, it seems I'd been reading your answer wrong, thanks for the help again! I wish I'd been more thorough in my initial reading of your answer...
  • Fermin Silva
    Fermin Silva over 7 years
    No problem dude :)
  • Goran B.
    Goran B. over 5 years
    plotly.offline.plot(data, include_plotlyjs="cdn", output_type="div") ... will give you a div with the necessary plotly js so that the div can just be embedded and you're done
  • Lou
    Lou over 3 years
    What is the plotly.js file? I'm attempting to implement this solution running a Python script in Linux, in order to create a Plotly graph and generate a HTML file. It produces a HTML file, but when opened the graph is blank. I'm not sure what you mean by adding the "plotly js" file to make this work.
  • Fermin Silva
    Fermin Silva over 3 years
    @Lou if you generate the entire html, then it should work out of the box. If you do like this answer suggests (create only the div and put it in a custom html yourself), then you need to include the plotly library in the page (the javascript file I mention). Open the html you generated with chrome and see the developer tools to see what error you are getting, and explore the html output
  • Lou
    Lou over 3 years
    Thanks for the response. I've been having some trouble getting the solution working (question link in case you have time and don't mind having a look) - I've added a reference to the JS in the head section of the HTML. It works on Chrome and IE in Windows, but not Firefox on Linux for some reason.
  • Jose Manuel Gomez Alvarez
    Jose Manuel Gomez Alvarez almost 2 years
    Beware of using hard drive as temporary storage of the html if you plan to serve it within the context of a dynamic web page, with real time constraints, because hard drive are far slower than memory, I much rather prefer to get html string in memory rather than writing file to disk, to read it afterwards.
  • Jose Manuel Gomez Alvarez
    Jose Manuel Gomez Alvarez almost 2 years
    Using filesystem is a no-go for dynamic web apps. It's very inefficient, unless you are generating static pages to be consumed many times, I very much prefer the plotly.io.to_html now.