Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
128 changes: 128 additions & 0 deletions doc/_dark_mode_figures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
"""Show every matplotlib figure in the docs together with a dark mode version.

This file runs at the start of each notebook kernel (through ``PYTHONSTARTUP``, set in
``conf.py``). Each figure is displayed twice: as is, and with the default black and
white colors (text, axes, ticks, legend frame, background) temporarily swapped for
dark mode ones. Nothing is executed twice, and the data colors are kept. The outputs
are tagged with the pydata-sphinx-theme ``only-light`` / ``only-dark`` classes, which
``conf.py`` passes on to the image nodes.
"""

from collections.abc import Callable, Iterator
from contextlib import contextmanager
from typing import Any

import matplotlib.colors as mcolors
from IPython import get_ipython
from IPython.display import display
from matplotlib.collections import Collection
from matplotlib.figure import Figure
from matplotlib.lines import Line2D
from matplotlib.patches import Patch
from matplotlib.text import Text

# the pydata-sphinx-theme dark mode text and background colors
DARK_MODE_FOREGROUND = "#ced6dd"
DARK_MODE_BACKGROUND = "#14181e"
TRANSPARENT = (0, 0, 0, 0)

IMAGE_MIME_TYPES = ("image/png", "image/jpeg", "image/svg+xml")


def _dark_mode_color(
color: Any, white: Any
) -> tuple[float, float, float, float] | None:
"""Dark mode replacement of a black or white color, None to keep the color.

Black becomes the dark mode text color, white becomes ``white`` (None keeps it).
"""
if isinstance(color, str) and color in ("none", "auto", "face"):
return None
try:
r, g, b, a = mcolors.to_rgba(color)
except (TypeError, ValueError):
return None
if a == 0:
return None
if (r, g, b) == (0, 0, 0):
return mcolors.to_rgba(DARK_MODE_FOREGROUND, a)
if (r, g, b) == (1, 1, 1) and white is not None:
return mcolors.to_rgba(white, a if white != TRANSPARENT else None)
return None


@contextmanager
def dark_mode(fig: Figure) -> Iterator[None]:
"""Temporarily swap the black and white colors of ``fig`` for dark mode colors.

The white figure background becomes transparent, other white areas, lines and
edges (e.g. legend frames or the edges separating scatter markers) the page
background color. White text and the colors of colormapped data are kept.
"""
restore: list[tuple[Callable[[Any], Any], Any]] = []

def recolor(original: Any, setter: Callable[[Any], Any], white: Any) -> None:
if (color := _dark_mode_color(original, white)) is not None:
setter(color)
restore.append((setter, original))

try:
artists = fig.findobj()
# text boxes and annotation arrows are not children of their text
for text in [a for a in artists if isinstance(a, Text)]:
patches = (text.get_bbox_patch(), getattr(text, "arrow_patch", None))
artists += [patch for patch in patches if patch is not None]
for obj in artists:
if isinstance(obj, Text):
recolor(obj.get_color(), obj.set_color, None)
elif isinstance(obj, Line2D):
line = DARK_MODE_BACKGROUND
recolor(obj.get_color(), obj.set_color, line)
recolor(obj.get_markeredgecolor(), obj.set_markeredgecolor, line)
recolor(obj.get_markerfacecolor(), obj.set_markerfacecolor, line)
elif isinstance(obj, Patch):
# the figure background shows the page, others (axes, legend frame)
# must keep covering what is behind them
face = TRANSPARENT if obj is fig.patch else DARK_MODE_BACKGROUND
recolor(obj.get_facecolor(), obj.set_facecolor, face)
recolor(obj.get_edgecolor(), obj.set_edgecolor, DARK_MODE_BACKGROUND)
elif isinstance(obj, Collection):
# only single colors: per element colors are data
edgecolors = obj.get_edgecolor()
if len(edgecolors) == 1:
recolor(edgecolors[0], obj.set_edgecolor, DARK_MODE_BACKGROUND)
# and so are the face colors of colormapped collections
facecolors = obj.get_facecolor()
if obj.get_array() is None and len(facecolors) == 1:
recolor(facecolors[0], obj.set_facecolor, DARK_MODE_BACKGROUND)
yield
finally:
for setter, original in reversed(restore):
setter(original)


def _with_classes(classes: str) -> dict[str, dict[str, str]]:
return {mime_type: {"classes": classes} for mime_type in IMAGE_MIME_TYPES}


_formatter = get_ipython().display_formatter.ipython_display_formatter


def display_with_dark_mode(fig: Figure) -> None:
"""IPython display formatter for figures that also shows the dark mode version.

Covers figures shown by the inline backend (at the end of a cell or by
``plt.show()``) and figures returned as the last expression of a cell.
"""
# IPython treats every figure as handled by this formatter, so switch it off
# to render the figure itself
_formatter.enabled = False
try:
display(fig, metadata=_with_classes("only-light"))
with dark_mode(fig):
display(fig, metadata=_with_classes("only-dark"))
finally:
_formatter.enabled = True


_formatter.for_type(Figure, display_with_dark_mode)
7 changes: 7 additions & 0 deletions doc/_static/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,10 @@ html[data-theme="dark"] div.cell_output .text_html:has(div.xr-wrap) {
background-color: var(--pst-color-on-background) !important;
color: var(--pst-color-text-base) !important;
}

/* the theme puts a light background behind cell output images in dark mode, but the
dark mode versions of matplotlib figures (see _dark_mode_figures.py) are meant to be
shown on the page background */
html[data-theme="dark"] .bd-content div.cell_output img.only-dark {
background-color: transparent;
}
21 changes: 21 additions & 0 deletions doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
import sys
from contextlib import suppress
from textwrap import dedent, indent
import docutils.nodes
import packaging.version
import sphinx_autosummary_accessors
import yaml
from myst_nb.core.render import MimeData, NbElementRenderer
from sphinx.application import Sphinx
from sphinx.ext.autodoc import (
AttributeDocumenter,
Expand Down Expand Up @@ -86,6 +88,25 @@
nb_execution_excludepatterns = ["examples/apply_ufunc_vectorize_1d.ipynb"]
# RTD does not publish the .err.log report, so print tracebacks in the build log
nb_execution_show_tb = True
# show matplotlib figures with a dark mode version, see _dark_mode_figures.py
_dark_mode_figures = pathlib.Path(__file__).with_name("_dark_mode_figures.py")
os.environ["PYTHONSTARTUP"] = str(_dark_mode_figures)

_render_image = NbElementRenderer.render_image


def _render_image_with_classes(
self: NbElementRenderer, data: MimeData
) -> list[docutils.nodes.Element]:
"""Also apply the ``classes`` of the output metadata, which myst-nb ignores."""
image_nodes = _render_image(self, data)
classes = data.output_metadata.get(data.mime_type, {}).get("classes", "")
for node in image_nodes:
node["classes"] += classes.split()
return image_nodes


NbElementRenderer.render_image = _render_image_with_classes # type: ignore[method-assign]

# AutoDoc configuration
autosummary_generate = True
Expand Down
4 changes: 2 additions & 2 deletions doc/examples/visualization_gallery.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,12 @@
" transform=ccrs.PlateCarree(), # the data's projection\n",
" col=\"time\",\n",
" col_wrap=1, # multiplot settings\n",
" aspect=ds.dims[\"lon\"] / ds.dims[\"lat\"], # for a sensible figsize\n",
" aspect=ds.sizes[\"lon\"] / ds.sizes[\"lat\"], # for a sensible figsize\n",
" subplot_kws={\"projection\": map_proj},\n",
") # the plot's projection\n",
"\n",
"# We have to set the map's options on all axes\n",
"for ax in p.axes.flat:\n",
"for ax in p.axs.flat:\n",
" ax.coastlines()\n",
" ax.set_extent([-160, -30, 5, 75])"
]
Expand Down
2 changes: 1 addition & 1 deletion doc/gallery/plot_cartopy_facetgrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
)

# We have to set the map's options on all four axes
for ax in p.axes.flat:
for ax in p.axs.flat:
ax.coastlines()
ax.set_extent([-160, -30, 5, 75])
# Without this aspect attributes the maps will look chaotic and the
Expand Down
2 changes: 1 addition & 1 deletion doc/user-guide/plotting.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ In this example `axs` is an array consisting of the left and right
axes created by `plt.subplots`.

```{code-cell}
fig, axs = plt.subplots(ncols=2)
fig, axs = plt.subplots(ncols=2, figsize=(12, 4), layout="constrained")

print(axs)

Expand Down
Loading