Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Sphinx example gallery #267

Draft
wants to merge 22 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
2193de8
[WIP] Add a sphinx-gallery example
tpvasconcelos Feb 5, 2023
9de417d
Merge branch 'main' into 88-plotly-in-sphinx
tpvasconcelos Jan 11, 2024
059837f
Merge branch 'main' into 88-plotly-in-sphinx
tpvasconcelos Oct 4, 2024
a16d042
Merge branch 'main' into 88-plotly-in-sphinx
tpvasconcelos Oct 6, 2024
da21aae
Merge branch 'main' into 88-plotly-in-sphinx
tpvasconcelos Oct 16, 2024
75bbf81
Merge branch 'main' into 88-plotly-in-sphinx
tpvasconcelos Oct 17, 2024
ed33315
Merge branch 'main' into 88-plotly-in-sphinx
tpvasconcelos Oct 22, 2024
a5d9d11
Merge branch 'main' into 88-plotly-in-sphinx
tpvasconcelos Oct 28, 2024
c8adf57
Update plot_probly.py example
tpvasconcelos Oct 28, 2024
3b61f96
Remove docs/examples_gallery_out/ artifacts from git
tpvasconcelos Oct 28, 2024
7e5108e
Add `sphinx_gallery_overwrite.css` CSS override
tpvasconcelos Oct 28, 2024
5618d69
Update cross-reference to ridgeplot function
tpvasconcelos Oct 28, 2024
39f4999
Update docs.txt
tpvasconcelos Oct 28, 2024
1cd0e71
Remove dead `rm -rf docs/jupyter_execute`
tpvasconcelos Oct 28, 2024
518e8f0
Remove dead `rm -rf docs/jupyter_execute`
tpvasconcelos Oct 28, 2024
77a1d43
Remove usage of `plotly.io.show()`
tpvasconcelos Oct 28, 2024
e021ee2
Update `sphinx_gallery_conf`
tpvasconcelos Nov 3, 2024
13d2c49
Add `rename_plotly_io_show` as a Sphinx `builder-inited` hook
tpvasconcelos Nov 4, 2024
bbef08c
Merge branch 'main' into 88-plotly-in-sphinx
tpvasconcelos Nov 18, 2024
3076914
Merge branch 'main' into 88-plotly-in-sphinx
tpvasconcelos Dec 5, 2024
a242959
Merge branch 'main' into 88-plotly-in-sphinx
tpvasconcelos Dec 23, 2024
16172bf
Merge branch 'main' into 88-plotly-in-sphinx
tpvasconcelos Dec 24, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
docs/_static/charts
docs/api/autogen
docs/api/public
docs/examples_gallery_out/
docs/sg_execution_times.rst


# ============================================================================
Expand Down
2 changes: 2 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ recursive-include docs/_static/css *.css
recursive-include docs/_static/img *.png *.webp *.svg *.gif *.jpg
recursive-include docs/_static/js *.js
recursive-include docs/_templates *.html
exclude docs/sg_execution_times.rst
prune docs/examples_gallery_out
prune docs/_build
prune docs/_static/charts
prune docs/api/autogen
Expand Down
3 changes: 2 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ clean-all: clean-docs clean-build clean-pyc clean-cov clean-ci-caches clean-tox
.PHONY: clean-docs
clean-docs: ## remove documentation build artifacts
@echo "==> Removing documentation build artifacts..."
rm -fr docs/_build/ docs/_static/charts docs/api/autogen/ docs/api/public/
rm -fr docs/_build/ docs/_static/charts docs/api/autogen/ docs/api/public/ docs/examples_gallery_out
rm -f docs/sg_execution_times.rst


.PHONY: clean-build
Expand Down
3 changes: 3 additions & 0 deletions docs/_static/css/sphinx_gallery_overwrite.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
div.sphx-glr-download-link-note {
display: none;
}
30 changes: 30 additions & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
# "sphinx_autodoc_typehints",
"sphinx_copybutton",
"sphinx_design",
"sphinx_gallery.gen_gallery",
"sphinx_inline_tabs",
"sphinx_paramlinks",
"sphinx_remove_toctrees",
Expand Down Expand Up @@ -119,6 +120,7 @@

html_css_files = [
"css/misc_overrides.css",
"css/sphinx_gallery_overwrite.css",
"css/versionmodified_admonitions.css",
# FontAwesome CSS for footer icons
# https://fontawesome.com/search
Expand Down Expand Up @@ -341,6 +343,18 @@
remove_from_toctrees = ["api/internal/*"]


# -- sphinx-gallery config -------------------------------------------------------------------------
sphinx_gallery_conf = {
"examples_dirs": "examples_gallery_in",
"gallery_dirs": "examples_gallery_out",
"run_stale_examples": True,
"download_all_examples": False,
"image_scrapers": ("plotly.io._sg_scraper.plotly_sg_scraper",),
"show_memory": False,
"show_signature": False,
"min_reported_time": 6,
}

# -- sphinx-paramlinks -----------------------------------------------------------------------------
paramlinks_hyperlink_param = "name"

Expand Down Expand Up @@ -413,6 +427,21 @@ def compile_all_plotly_charts() -> None:
end_of_file_fixer(files)


def rename_plotly_io_show() -> None:
"""Rename usages of `plotly.io.show` to `fig.show`."""
from pathlib import Path

for file in Path("examples_gallery_out/").iterdir():
if file.suffix not in {".py", ".rst", ".ipynb"}:
continue
new_lines = []
for line in file.read_text().split("\n"):
if "import plotly.io as pio" in line:
continue
new_lines.append(line.replace("pio.show(fig)", "fig.show()"))
file.write_text("\n".join(new_lines))


def dispatch(fn: Callable[[], None]) -> Callable[..., None]:
def wrapper(*args: Any, **kwargs: Any) -> None:
fn()
Expand All @@ -422,4 +451,5 @@ def wrapper(*args: Any, **kwargs: Any) -> None:

def setup(app: Sphinx) -> None:
# app.connect("builder-inited", dispatch(write_plotlyjs_bundle), priority=501)
app.connect("builder-inited", dispatch(rename_plotly_io_show))
app.connect("builder-inited", dispatch(compile_all_plotly_charts), priority=502)
7 changes: 7 additions & 0 deletions docs/examples_gallery_in/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
:hide-toc:

Examples gallery
==================

This page contains example plots. Click on a thumbnail to see the full
graph and source code.
83 changes: 83 additions & 0 deletions docs/examples_gallery_in/plot_probly.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
"""
probly dataset
=================

In this example, we will be replicating the first ridgeline plot example in
`this _from Data to Viz_ post <https://www.data-to-viz.com/graph/ridgeline.html>`_
, which uses the _probly_ dataset. You can find the _plobly_ dataset on
multiple sources like in the
`bokeh <https://raw.githubusercontent.com/bokeh/bokeh/main/bokeh/sampledata/_data/probly.csv>`_
python interactive visualization library. I'll be using the
`same source <https://raw.githubusercontent.com/zonination/perceptions/master/probly.csv>`_
used in the original post.
"""

from __future__ import annotations

import numpy as np
import plotly.io as pio

from ridgeplot import ridgeplot
from ridgeplot.datasets import load_probly

# %%
# Load the probly dataset
df = load_probly()

# %%
# Let's grab the subset of columns used in the example
column_names = [
"Almost Certainly",
"Very Good Chance",
"We Believe",
"Likely",
"About Even",
"Little Chance",
"Chances Are Slight",
"Almost No Chance",
]
df = df[column_names]

# %%
# Not only does :func:`~ridgeplot.ridgeplot()` come configured with sensible defaults
# but is also fully configurable to your own style and preference!

fig = ridgeplot(
# Get your samples in the correct format
samples=df.to_numpy().T,
# We can specify the bandwidth used for KDE
bandwidth=4,
# and the range of points for which the KDE is evaluated
kde_points=np.linspace(-12.5, 112.5, 500),
# You can pass any plotly color scale here
colorscale="viridis",
# In the example, the distributions seem to be colored the
# row's index. Have a look at the other available options!
colormode="row-index",
# Set the transparency level
opacity=0.65,
# Always label your plots! Don't be evil...
labels=column_names,
# Adjust the vertical spacing between the distributions
spacing=5 / 9,
)

# %%
# And you can still update and extend the final
# Plotly Figure using standard Plotly methods
fig.update_layout(
height=560,
width=800,
font_size=16,
plot_bgcolor="white",
xaxis_tickvals=[-12.5, 0, 12.5, 25, 37.5, 50, 62.5, 75, 87.5, 100, 112.5],
xaxis_ticktext=["", "0", "", "25", "", "50", "", "75", "", "100", ""],
xaxis_gridcolor="rgba(0, 0, 0, 0.1)",
yaxis_gridcolor="rgba(0, 0, 0, 0.1)",
yaxis_title=dict(text="Assigned Probability (%)", font_size=13),
showlegend=False,
)

# %%
# Show us the work!
pio.show(fig)
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ hidden: true
---
getting_started/installation
getting_started/getting_started
examples_gallery_out/index.rst
```

```{toctree}
Expand Down
13 changes: 11 additions & 2 deletions requirements/docs.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,17 @@ sphinx_thebe
sphinxcontrib-apidoc
sphinxext-opengraph

# matplotlib is used to generate social cards
# Sphinx-Gallery dependencies
sphinx-gallery
# kaleido is used to export static images from Plotly
# figures, which is used by sphinx-gallery to generate
# thumbnails for the examples gallery
kaleido
# matplotlib is an implicit dependency of sphinx-gallery.
# although we don't need it for this project, we
# still need to declare the dependency here.
matplotlib

# Cleanup generated files
# Use the `pre_commit_hooks` Python package to cleanup
# generated files as 'build-finished' Sphinx hooks
pre_commit_hooks
8 changes: 6 additions & 2 deletions ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,12 @@ ignore = [
"D100", # Missing docstring in public module
"ARG001", # Unused function argument
"INP001", # File {x} is part of an implicit namespace package. Add an `__init__.py`
"S101", # Use of assert detected
"T201", # `print` found
"T201", # `print` found
]
"docs/examples_gallery_in/*" = [
"INP001", # File {x} is part of an implicit namespace package. Add an `__init__.py`.
"B018", # Found useless expression. Either assign it to a variable or remove it.
"T201", # `print` found
]
"tests/*" = [
"D100", # Missing docstring in public module
Expand Down
Loading