Skip to content
Merged
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ to [Semantic Versioning](https://semver.org/).

### Added

- The font chain reaches metric-compatible Helvetica clones (TeX Gyre Heros, Nimbus Sans, Liberation Sans) before DejaVu Sans.
- `register_fonts(dir)` (default `$NICEFIGS_FONT_DIR`) makes a folder of fonts available to a theme; the themes' fonts
are unchanged. SVG text is written as paths (`svg.fonttype="path"` in every theme and in `save`); text
keeps the list of installed families it was created with, so a figure saved after its theme context
still uses them.
- `use_agg()`, called by `figure` and `subplots`: selects the Agg backend unless a backend was chosen.
- `scorecard` draws the PhD-defense-deck look: text is the raw value, colour the percent better
than a baseline on the fixed 11-band `scorecard_skill_cmap` (blue better, red worse).
New arguments: `color_values` and `text` (colour numbers apart from printed ones),
Expand Down
5 changes: 4 additions & 1 deletion src/nicefigs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
flux_diagram,
flux_legend,
)
from .figure import TextIssue, check_text_overlaps, figure, figure_size, save, subplots
from .figure import TextIssue, check_text_overlaps, figure, figure_size, save, subplots, use_agg
from .hovmoller import hovmoller, hovmoller_panels
from .images import heatmap, image, image_grid, overlay_grid, pca_rgb
from .kde import agreement, kde_contours, scatter_regression
Expand Down Expand Up @@ -105,6 +105,7 @@
THEMES,
Theme,
get_theme,
register_fonts,
set_theme,
style,
)
Expand Down Expand Up @@ -157,6 +158,8 @@
"subplots",
"figure_size",
"save",
"use_agg",
"register_fonts",
"check_text_overlaps",
"TextIssue",
# panels
Expand Down
32 changes: 29 additions & 3 deletions src/nicefigs/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from pathlib import Path
from typing import Any

import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.text import Text
Expand Down Expand Up @@ -106,6 +107,17 @@ def figure_size(
return WIDTHS["half"], WIDTHS["half"] * DEFAULT_ASPECT


def use_agg() -> None:
"""Select the Agg backend unless a backend was already chosen (``MPLBACKEND`` or ``matplotlib.use``).

Building a figure on an interactive backend connects to a window system, which takes tens of
seconds over X forwarding; Agg takes under two. A backend the user chose is never overridden.
"""
chosen = getattr(mpl.rcParams, "_get_backend_or_none", lambda: None)()
if chosen is None:
mpl.use("agg")


def figure(
width: float | str | None = None,
height: float | None = None,
Expand All @@ -129,6 +141,7 @@ def figure(
"""
size = figure_size(width, height, aspect)
th = get_theme(theme)
use_agg()
with style(th):
fig = plt.figure(figsize=size, dpi=th.dpi, **kwargs)
return fig
Expand Down Expand Up @@ -172,6 +185,7 @@ def subplots(
if gridspec_kw:
kwargs["gridspec_kw"] = gridspec_kw
th = get_theme(theme)
use_agg()
with style(th):
fig, axes = plt.subplots(nrows, ncols, figsize=size, dpi=th.dpi, **kwargs)
return fig, axes
Expand Down Expand Up @@ -207,6 +221,21 @@ def save(
th = get_theme()
dpi = dpi or th.savedpi
paths = []
with mpl.rc_context({"svg.fonttype": "path"}): # SVG text as paths: fonts need not be installed
_write(fig, p, formats, dpi, transparent, paths)
if close:
plt.close(fig)
return paths


def _write(
fig: Figure,
p: Path,
formats: tuple[str, ...] | None,
dpi: int,
transparent: bool,
paths: list[Path],
) -> None:
if formats is None:
p.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(p, dpi=dpi, bbox_inches="tight", pad_inches=0.02, transparent=transparent)
Expand All @@ -218,9 +247,6 @@ def save(
out = stem.with_suffix(f".{ext.lstrip('.')}")
fig.savefig(out, dpi=dpi, bbox_inches="tight", pad_inches=0.02, transparent=transparent)
paths.append(out)
if close:
plt.close(fig)
return paths


@dataclass(frozen=True)
Expand Down
50 changes: 48 additions & 2 deletions src/nicefigs/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@
from __future__ import annotations

import contextlib
import os
from collections.abc import Iterator
from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Any

import matplotlib as mpl
Expand Down Expand Up @@ -87,6 +89,34 @@
# --------------------------------------------------------------------------- #


FONT_DIR_ENV = "NICEFIGS_FONT_DIR"
_FONTS_ADDED: set[str] = set()


def register_fonts(directory: str | os.PathLike[str] | None = None) -> list[str]:
"""Make the fonts of a directory known to matplotlib, so a theme can list their family.

Opt-in: nothing calls it for you and the themes' fonts are unchanged. Register fonts, then use a
theme such as ``Theme(sans_serif=("Fira Sans", "DejaVu Sans"))``.

Args:
directory: Folder of ``.otf``/``.ttf`` files; defaults to ``$NICEFIGS_FONT_DIR`` (none if unset).

Returns:
The font family names now available from that folder (empty if there is none).
"""
from matplotlib import font_manager as fm

folder = directory if directory is not None else os.environ.get(FONT_DIR_ENV)
if not folder:
return []
for path in sorted(Path(folder).glob("*.[ot]tf")):
if str(path) not in _FONTS_ADDED:
_FONTS_ADDED.add(str(path))
fm.fontManager.addfont(str(path))
return sorted({f.name for f in fm.fontManager.ttflist if Path(f.fname).parent == Path(folder)})


@dataclass(frozen=True)
class Theme:
"""A frozen bundle of styling parameters.
Expand Down Expand Up @@ -134,7 +164,16 @@ class Theme:
spine_color: str = "#222222"

font_family: str = "sans-serif"
sans_serif: tuple[str, ...] = ("Helvetica", "Arial", "DejaVu Sans", "sans-serif")
sans_serif: tuple[str, ...] = (
"Helvetica",
"Arial",
"TeX Gyre Heros",
"Nimbus Sans",
"Nimbus Sans L",
"Liberation Sans",
"DejaVu Sans",
"sans-serif",
)

spines_topright: bool = False
grid: bool = False
Expand Down Expand Up @@ -191,14 +230,21 @@ def with_(self, **overrides: Any) -> Theme:

def rc(self) -> dict[str, Any]:
"""Render this theme as a matplotlib ``rcParams`` dict."""
# Text keeps the family list it was created with, so a figure drawn or saved after the theme
# context ended uses the same fonts; only installed families are listed (no findfont warnings).
from matplotlib import font_manager as fm

installed = {f.name for f in fm.fontManager.ttflist} | {"sans-serif"}
family = [f for f in self.sans_serif if f in installed]
return {
"svg.fonttype": "path",
"figure.dpi": self.dpi,
"savefig.dpi": self.savedpi,
"savefig.bbox": "tight",
"savefig.pad_inches": 0.015,
"figure.facecolor": "white",
"savefig.facecolor": "white",
"font.family": self.font_family,
"font.family": family if self.font_family == "sans-serif" else self.font_family,
"font.sans-serif": list(self.sans_serif),
"font.size": self.fs_body,
"text.color": self.text_color,
Expand Down
39 changes: 39 additions & 0 deletions tests/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,42 @@ def test_palettes_are_nonempty_hex_lists():
assert len(pal) > 0
for c in pal:
assert c.startswith("#")


def test_rc_keeps_helvetica_first_and_converts_svg_text_to_paths():
chain = THEMES["paper-large"].sans_serif
assert chain[:2] == ("Helvetica", "Arial")
assert chain.index("Liberation Sans") < chain.index("DejaVu Sans") # a Helvetica look-alike before DejaVu
assert THEMES["paper-large"].rc()["svg.fonttype"] == "path"


def test_use_agg_keeps_a_chosen_backend_and_picks_agg_otherwise(monkeypatch):
import matplotlib as mpl

calls = []
monkeypatch.setattr(mpl, "use", lambda b: calls.append(b))
monkeypatch.setattr(mpl.rcParams.__class__, "_get_backend_or_none", lambda self: "tkagg", raising=False)
nf.use_agg()
assert calls == []
monkeypatch.setattr(mpl.rcParams.__class__, "_get_backend_or_none", lambda self: None, raising=False)
nf.use_agg()
assert calls == ["agg"]


def test_save_writes_svg_without_text_elements(tmp_path):
fig, ax = nf.subplots(width="half")
ax.set_title("hello")
(svg,) = nf.save(fig, tmp_path / "f", formats=("svg",))
assert "<text" not in svg.read_text()


def test_register_fonts_makes_a_folders_family_available_without_changing_themes(tmp_path):
import shutil

import matplotlib.font_manager as fm

shutil.copy(fm.findfont("DejaVu Sans"), tmp_path / "x.ttf")
before = THEMES["paper"].sans_serif
assert "DejaVu Sans" in nf.register_fonts(tmp_path)
assert nf.register_fonts(tmp_path / "missing") == []
assert THEMES["paper"].sans_serif == before
Loading
Loading