Interactive plots: plotly

import matplotlib
if not hasattr(matplotlib.RcParams, "_get"):
    matplotlib.RcParams._get = dict.get

Interactive plots: plotly#

The use of the plotly package is an example which allows you to create HTML/Javascript widgets from python code without any knowledge on HTML/Javascript. The example below is taken from the FEM-module by Frans van der Meer.

If you want to create the plot during the build of the book, don’t use fig.show() but use the code below:

from IPython import get_ipython
from IPython.display import HTML

def show_plotly(fig):
    ip = get_ipython()
    if ip is None:
        return fig

    # Sphinx / Jupyter Book execution
    if "sphinx" in ip.config:
        return HTML(fig.to_html(include_plotlyjs="cdn"))

    # Local execution in Jupyter Notebook / JupyterLab / VS Code
    fig.show()

....

show_plotly(fig)

Make sure you have in your _config.yml:

execute:
  execute_notebooks: "auto"

Eventually in combination with NoteBook Execution Patterns

When using Plotly graphs, make sure the notebook is executed in Jupyter Lab / Jupyter Notebook for the figures to be shown in the book. Running the code in VS code might break the result in the book, although the output is visible in VS code. Alternatively, add the following lines of code to your notebook to have a valid output in the book as well:

import plotly.io as pio
pio.renderers.default = 'notebook'