Search code examples
pythonemacsplotlyorg-mode

Embed plotly diagram in html document from orgmode


I have a python script inside a orgmode document that creates a diagram with plotly (which works fine). Now I want the results block to show the diagram on html export. Here is my example document:

#+title: test with plotly in org
#+author: Thats Me
#+html_head: <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>

* My Chapter
Python code with plotly here.
#+begin_src python
  import plotly.express as px

  fig = px.line(x=[0,1,2,3,4], y=[0,1,4,9,16])
  fig.show()
  fig.write_html("out.html", include_plotlyjs=True, full_html=True)
#+end_src

#+RESULTS:
: None

[[file:out.html]]

#+include: out.html html

The link is unfortunately only a clickable link, which leads to the file (and if the arguments include_plotlyjs and full_html are set properly, will be displayed correctly). But I would like to see the diagram directly below the text.

With the include command I unfortunately only get a text output and not the diagram. Also it comes to an error message "Unable to resolve link: "0"" when the argument include_plotlyjs=True is set.

What is your approach to export plotly graphics from orgmode documents into html?


Solution

  • For all those who are trying the same thing, I have found a solution after much trial and error:

    #+begin_src python :results raw html :exports both
      import plotly.offline as pyo
      import plotly.graph_objs as go
    
      trace = go.Scatter(x=[0,1,2,3,4], y=[0,1,4,9,16])
      fig = go.Figure(data=[trace])
      fig_html = pyo.plot(fig, include_plotlyjs=True, output_type='div')
      return fig_html.encode()
    #+end_src