Skip to content

Commit

Permalink
DX: support Plotly in static webpages (#208)
Browse files Browse the repository at this point in the history
* DOC: add `plotly` with `ipywidgets example to TR-006
* DOC: add `plotly` example notebook TR-023
* DX: import JS files through `html_js_files`
* FIX: update `ipywidgets`
  Using `ipywidgets` <v8 causes Javascript error
  • Loading branch information
redeboer authored Sep 27, 2023
1 parent e780376 commit 16b76be
Show file tree
Hide file tree
Showing 6 changed files with 270 additions and 4 deletions.
3 changes: 3 additions & 0 deletions .cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@
"parametrizations",
"pathlib",
"permutate",
"Plotly",
"pyproject",
"pytest",
"PYTHONHASHSEED",
Expand Down Expand Up @@ -151,6 +152,7 @@
"codegen",
"codemirror",
"colorbar",
"colorscale",
"colspan",
"combi",
"commitlint",
Expand Down Expand Up @@ -311,6 +313,7 @@
"subslide",
"substack",
"suptitle",
"surfacecolor",
"symplot",
"tbody",
"thead",
Expand Down
7 changes: 6 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,10 @@ def fetch_logo(url: str, output_path: str) -> None:
graphviz_output_format = "svg"
html_copy_source = True # needed for download notebook button
html_favicon = "_static/favicon.ico"
html_js_files = [
"https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js",
"https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js",
]
html_last_updated_fmt = "%-d %B %Y"
html_show_copyright = False
html_show_sourcelink = False
Expand Down Expand Up @@ -265,6 +269,7 @@ def get_minor_version(package_name: str) -> str:
None,
),
"numpy": (f"https://numpy.org/doc/{get_minor_version('numpy')}", None),
"plotly": ("https://plotly.com/python-api-reference/", None),
"pwa": ("https://pwa.readthedocs.io", None),
"python": ("https://docs.python.org/3", None),
"qrules": ("https://qrules.readthedocs.io/en/stable", None),
Expand All @@ -282,6 +287,7 @@ def get_minor_version(package_name: str) -> str:
bibtex_bibfiles = ["bibliography.bib"]
suppress_warnings = [
"myst.domains",
"mystnb.unknown_mime_type",
]

# Settings for copybutton
Expand Down Expand Up @@ -326,7 +332,6 @@ def print_once(message: str) -> None:
"report/002*",
"report/003*",
"report/005*",
"report/006*",
"report/008*",
"report/009*",
"report/01*",
Expand Down
94 changes: 93 additions & 1 deletion docs/report/006.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
},
"outputs": [],
"source": [
"%pip install -q ipywidgets==7.6.5 matplotlib==3.4.3 numpy==1.19.5 sympy==1.8"
"%pip install -q ipywidgets==8.1.1 matplotlib==3.4.3 numpy==1.19.5 plotly==5.17.0 sympy==1.8"
]
},
{
Expand Down Expand Up @@ -109,6 +109,7 @@
"\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import plotly.graph_objects as go\n",
"import sympy as sp\n",
"from IPython.display import display\n",
"from ipywidgets import widgets as ipywidgets\n",
Expand Down Expand Up @@ -457,6 +458,97 @@
"\n",
"![ipywidgets interactive output with interactive_output()](https://user-images.githubusercontent.com/29308176/164993430-6f6b906a-dfb5-4c7c-bae5-d9951c02112b.gif)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Plotly with ipywidgets"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"3D plots with [Plotly](https://plotly.com/python) look a lot nicer and make it possible for the user to pan and zoom the 3D object. As an added bonus, Plotly figures [render as interactive 3D objects](https://myst-nb.readthedocs.io/en/v0.17.2/render/interactive.html#plotly) in the static HTML Sphinx build.\n",
"\n",
"Making 3D Plotly plots interactive with {mod}`ipywidgets` is quite similar to the previous examples with {mod}`matplotlib`. Two recommendations are:\n",
"\n",
"1. Set `continuous_update=False`, because {mod}`plotly` is slower than {mod}`matplotlib` in updating the figure.\n",
"2. Save the camera orientation and update it after calling `Figure.show()`.\n",
"3. When embedding the notebook a static webpage with [MyST-NB](https://myst-nb.readthedocs.io), avoid calling `Figure.show()` through [`ipywidgets.interactive_output()`](https://ipywidgets.readthedocs.io/en/stable/examples/Using%20Interact.html), because it causes the notebook to hang in some cycle (see CI for [ComPWA/compwa-org@d9240f1](https://github.com/ComPWA/compwa-org/pull/208/commits/d9240f1)). In the example below, the `update_plotly()` function is aborted if the notebook is run through Sphinx. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"hide-input"
]
},
"outputs": [],
"source": [
"plotly_a = ipywidgets.FloatSlider(\n",
" description=f\"${sp.latex(a)}$\",\n",
" value=a_init,\n",
" min=-2,\n",
" max=2,\n",
" step=0.1,\n",
" continuous_update=False,\n",
" readout_format=\".1f\",\n",
")\n",
"plotly_b = ipywidgets.IntSlider(\n",
" description=f\"${sp.latex(b)}$\",\n",
" value=b_init,\n",
" min=10,\n",
" max=50,\n",
" continuous_update=False,\n",
")\n",
"plotly_controls = {\"a\": plotly_a, \"b\": plotly_b}\n",
"\n",
"plotly_surface = go.Surface(\n",
" x=X,\n",
" y=Y,\n",
" z=Z,\n",
" surfacecolor=Z,\n",
" colorscale=\"RdBu_r\",\n",
" name=\"Surface\",\n",
")\n",
"plotly_fig = go.Figure(data=[plotly_surface])\n",
"plotly_fig.update_layout(height=500)\n",
"if STATIC_WEB_PAGE:\n",
" plotly_fig.show()\n",
"\n",
"\n",
"def update_plotly(a, b):\n",
" if STATIC_WEB_PAGE:\n",
" return\n",
" Z = numpy_function(X, Y, a, b)\n",
" camera_orientation = plotly_fig.layout.scene.camera\n",
" plotly_fig.update_traces(\n",
" x=X,\n",
" y=Y,\n",
" z=Z,\n",
" surfacecolor=Z,\n",
" selector=dict(name=\"Surface\"),\n",
" )\n",
" plotly_fig.show()\n",
" plotly_fig.update_layout(scene=dict(camera=camera_orientation))\n",
"\n",
"\n",
"plotly_ui = ipywidgets.HBox([plotly_a, plotly_b])\n",
"plotly_output = ipywidgets.interactive_output(update_plotly, plotly_controls)\n",
"display(plotly_ui, plotly_output)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
":::{seealso} {doc}`/report/023`\n",
":::"
]
}
],
"metadata": {
Expand Down
167 changes: 167 additions & 0 deletions docs/report/023.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"hideCode": true,
"hideOutput": true,
"hidePrompt": true,
"jupyter": {
"source_hidden": true
},
"slideshow": {
"slide_type": "skip"
},
"tags": [
"remove-cell"
]
},
"outputs": [],
"source": [
"%config InlineBackend.figure_formats = ['svg']\n",
"import os\n",
"\n",
"STATIC_WEB_PAGE = {\"EXECUTE_NB\", \"READTHEDOCS\"}.intersection(os.environ)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```{autolink-concat}\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"tags": [
"documentation",
"jupyter",
"sphinx",
"3d"
]
},
"source": [
"::::{margin}\n",
":::{card} Support for Plotly plots in Technical Reports\n",
"TR-023\n",
"^^^\n",
"+++\n",
"✅&nbsp;[compwa-org#206](https://github.com/ComPWA/compwa-org/issues/206)\n",
":::\n",
"::::"
]
},
{
"cell_type": "markdown",
"metadata": {
"tags": []
},
"source": [
"# 3D plots with Plotly\n",
"<!-- cspell:ignore isomax isomin isosurface mgrid -->"
]
},
{
"cell_type": "markdown",
"metadata": {
"tags": [
"remove-cell"
]
},
"source": [
"<!-- cspell:ignore cstride darkred labelpad matexpr rstride zorder -->"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"jupyter": {
"source_hidden": true
},
"tags": [
"remove-cell"
]
},
"outputs": [],
"source": [
"%pip install -q numpy==1.20.3 plotly==5.17.0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This TR tests whether the HTML build of the TR notebooks supports [Plotly](https://plotly.com/python) figures. It's a follow-up to [TR-006](006.ipynb), without the interactivity of `ipywidgets`, but with the better 3D rendering of Plotly. For more info on how Plotly figures can be embedded in Sphinx HTML builds, see [this page](https://myst-nb.readthedocs.io/en/v0.17.2/render/interactive.html#plotly) of MyST-NB (particularly the remark on [`html_js_files`](https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-html_js_files).\n",
"\n",
"The following example is copied from [this tutorial](https://plotly.com/python/3d-isosurface-plots)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import plotly.graph_objects as go\n",
"\n",
"X, Y, Z = np.mgrid[-5:5:40j, -5:5:40j, -5:5:40j]\n",
"ellipsoid = X * X * 0.5 + Y * Y + Z * Z * 2\n",
"fig = go.Figure(\n",
" data=go.Isosurface(\n",
" x=X.flatten(),\n",
" y=Y.flatten(),\n",
" z=Z.flatten(),\n",
" value=ellipsoid.flatten(),\n",
" isomin=5,\n",
" isomax=50,\n",
" surface_fill=0.4,\n",
" caps=dict(x_show=False, y_show=False),\n",
" slices_z=dict(\n",
" show=True,\n",
" locations=[\n",
" -1,\n",
" -3,\n",
" ],\n",
" ),\n",
" slices_y=dict(show=True, locations=[0]),\n",
" )\n",
")\n",
"fig.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
":::{seealso} {ref}`report/006:Plotly with ipywidgets`\n",
":::"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.18"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
2 changes: 0 additions & 2 deletions docs/reports.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ well.
```

<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<script type="text/javascript" src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

<style>
td.details-control {
background: url('https://www.datatables.net/examples/resources/details_open.png') no-repeat center center;
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ ruff = [
"--extend-ignore=A003",
"--extend-ignore=B008",
"--extend-ignore=B018",
"--extend-ignore=C408",
"--extend-ignore=C90",
"--extend-ignore=D",
"--extend-ignore=F404",
Expand Down

0 comments on commit 16b76be

Please sign in to comment.