diff --git a/doc/_dark_mode_figures.py b/doc/_dark_mode_figures.py new file mode 100644 index 00000000000..c1171c3fe5b --- /dev/null +++ b/doc/_dark_mode_figures.py @@ -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) diff --git a/doc/_static/style.css b/doc/_static/style.css index 8a746f3828c..7ddba1852eb 100644 --- a/doc/_static/style.css +++ b/doc/_static/style.css @@ -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; +} diff --git a/doc/conf.py b/doc/conf.py index 4b28bb94c5a..bfbbd36b34e 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -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, @@ -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 diff --git a/doc/examples/visualization_gallery.ipynb b/doc/examples/visualization_gallery.ipynb index e7e9196a6f6..87bf4023dd9 100644 --- a/doc/examples/visualization_gallery.ipynb +++ b/doc/examples/visualization_gallery.ipynb @@ -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])" ] diff --git a/doc/gallery/plot_cartopy_facetgrid.py b/doc/gallery/plot_cartopy_facetgrid.py index faa148938d6..a9d299b3cf8 100644 --- a/doc/gallery/plot_cartopy_facetgrid.py +++ b/doc/gallery/plot_cartopy_facetgrid.py @@ -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 diff --git a/doc/user-guide/plotting.md b/doc/user-guide/plotting.md index 52c8d5979ce..9994542f414 100644 --- a/doc/user-guide/plotting.md +++ b/doc/user-guide/plotting.md @@ -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)