Search code examples
pythonhtmlpython-3.xplotlyplotly-express

returning a string from plotly's write_html


I'm trying to have plotly express return a string of a div object in html so I can integrate it with other packages. I am trying to follow the documentation (Plotly v5.17.0), and I feel like I'm doing what it tells me to do, but no success.

I'm not sure if I'm missing something obvious (apologies if so) but within the documents in Python I am seeing:

full_html: bool (default True) If True, produce a string containing a complete HTML document starting with an <html> tag. If False, produce a string containing a single <div> element.

and:

Returns ------- str Representation of figure as an HTML div string

Yet, while I can write this div element to a file no problem by making this call with div = fig.write_html(filename, full_html=False) it will return None every time.


Solution

  • I found issue in Plotly GitHub: plotly.io.write_html return · Issue #3599 · plotly/plotly.py

    It seems there is mistake in documentation. You have to use .to_html().

    div = fig.to_html(full_html=False)
    

    BTW:

    It generates string with ~ 3 600 000 chars(~ 3.5MB) because it includes all JavaScript code.

    Using include_plotlyjs=False you get only ~ 8 000 chars

    div = fig.to_html(full_html=False, include_plotlyjs=False)