Output of plotly to_html() method is not displayed in Jupyter Notebook

189 Views Asked by At

When creating an html from a plotly plot using the to_hmtl method, the generated html can be displayed correctly using display(HTML(x)) when using JupyterLab but is not displayed correctly when using Jupyter Notebook (nothing is displayed).

Also, when trying to export the Jupyter Lab notebook to hmtl using nbconvert, the plotly plot are not correctly shown in the generated html (although they are rendered correctly in the JupyterLab Notebook)

Python Code

# Import libraries
import plotly.graph_objs as go
from IPython.display import HTML, display

# Sample data
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]

# Create trace and figure
trace = go.Scatter(x=x, y=y)
fig = go.Figure(data=[trace])

# Generate html figure
html_fig = fig.to_html()

# Display the html figure (Works in JupyterLab. Does not work in Jupyter Notebook)
display(HTML(data=html_fig))

Terminal Code to Convert Notebook to html
jupyter nbconvert --to html PlotlyToHtml.ipynb

Versions

  • JuypterLab = 3.6.3
  • Notebook = 6.5.4
  • Python = 3.10.13
  • plotly = 5.9.0
  • IPython = 8.15.0
  • nbconvert = 6.5.4

What I tried (without success)

  1. Explicitely set pio renderer
    Set the pio renderer to "notebook" (and all other available renderer types) at the beginning of the jupyter notebook as suggested in some older posts
import plotly.io as pio
pio.renderers.default="notebook" # jupyterlab, vscode, ...
  1. Wrap html in an iframe
    Wrap the html figure in an iframe as suggested here: https://github.com/microsoft/vscode-jupyter/issues/3654
html_fig_modified = (
    """<iframe sandbox='allow-scripts allow-forms' style='display:block; margin:0px;' frameborder='0' srcdoc='
<!DOCTYPE html>"""
    + html_fig
    + """ />"""
)

HTML(html_fig_modified)
  1. Import holoview to allow exporting with nbconvert
    I tried to import holoview at the very beginning of the jupyter notebook (as suggested here https://github.com/plotly/plotly.py/issues/1033) to see if at least I could see the interactive figures after exporting the html with nbconvert. The exported html still does not render the interactive figure correctly.
import holoviews as hv
hv.extension("plotly")
  1. Set notebook mode to connected
    I try setting the notebook mode to connected as suggested in some posts.
from plotly.offline import init_notebook_mode
init_notebook_mode(connected=True)
0

There are 0 best solutions below