sci-figures 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.5
2
+ Name: sci-figures
3
+ Version: 0.3.0
4
+ Summary: Style, mm layout, recurring elements and export for Nature-style research figures with editable text.
5
+ Project-URL: Source, https://github.com/quadbio/sci-figures
6
+ Author: quadbio
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Programming Language :: Python :: 3 :: Only
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Requires-Python: >=3.12
14
+ Requires-Dist: matplotlib>=3.8
15
+ Provides-Extra: examples
16
+ Requires-Dist: anndata; extra == 'examples'
17
+ Requires-Dist: pyyaml; extra == 'examples'
18
+ Requires-Dist: scanpy>=1.10; extra == 'examples'
19
+ Provides-Extra: spatial-examples
20
+ Requires-Dist: anndata; extra == 'spatial-examples'
21
+ Requires-Dist: cellcharter>=0.3.7; extra == 'spatial-examples'
22
+ Requires-Dist: geopandas; extra == 'spatial-examples'
23
+ Requires-Dist: lightning; extra == 'spatial-examples'
24
+ Requires-Dist: pyyaml; extra == 'spatial-examples'
25
+ Requires-Dist: scanpy>=1.10; extra == 'spatial-examples'
26
+ Requires-Dist: shapely>=2; extra == 'spatial-examples'
27
+ Requires-Dist: sopa>=2.2; extra == 'spatial-examples'
28
+ Requires-Dist: spatialdata-plot>=0.4.2; extra == 'spatial-examples'
29
+ Requires-Dist: spatialdata>=0.8; extra == 'spatial-examples'
30
+ Requires-Dist: squidpy>=1.8; extra == 'spatial-examples'
31
+ Requires-Dist: torch; extra == 'spatial-examples'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # sci-figures
35
+
36
+ A Claude Code plugin for Nature-style research figures (main, Extended Data, supplementary) and their legends. The
37
+ agent writes the plotting code (matplotlib, seaborn, scanpy, spatialdata-plot); the skill says what the result must
38
+ achieve, from the figure's message to its export as one PDF with editable Arial text, and has independent reviewers
39
+ check the layout and the legend against the code.
40
+
41
+ | Part | What it does |
42
+ | --- | --- |
43
+ | `skills/sci-figures/` | The workflow, visual and legend conventions, the two reviews, setup, and two complete example figures (outline, script, legend). Loaded on demand. |
44
+ | `src/scifig/` | `apply_style`, mm layout (`new_figure`, `add_axes_mm`, `panel_letter`), recurring elements (`badge`, `colorbar`, `embedding_axes`, `scale_bar`) and `save`, which checks fonts, sizes and raster resolution. |
45
+
46
+ ## Use
47
+
48
+ Ask Claude for a figure, a panel or a legend in the repo that holds the figure scripts.
49
+
50
+ 1. It agrees the format and an outline with you (message, story line, one entry per panel) and saves the outline
51
+ next to the script.
52
+ 2. It computes the plotted data, then writes one script per figure that only loads and plots it.
53
+ 3. It checks the preview against the layout checklist, writes the legend from the code and the data, and runs the
54
+ layout and legend reviews in parallel.
55
+ 4. It shows you the PDF with its legend and lists the review findings it declined.
56
+
57
+ Colors and marks shared across a paper's figures live in the repo's `resources/figure_conventions.yaml`.
58
+
59
+ ## Install
60
+
61
+ **The plugin**, once per machine, from the [quadbio marketplace](https://github.com/quadbio/claude-plugins).
62
+
63
+ **The package**, Arial and TeX (for equations): [`skills/sci-figures/references/setup.md`](skills/sci-figures/references/setup.md).
64
+
65
+ ## Develop
66
+
67
+ ```bash
68
+ uv sync --group dev
69
+ uv run python -m scifig.fonts # Arial, once per machine
70
+ uv run pytest # the equation test is skipped without TeX
71
+ uv run pre-commit run --all-files
72
+ claude plugin validate .
73
+ claude --plugin-dir . # try the skill from this checkout
74
+ ```
75
+
76
+ The example figures: `uv run --extra examples python skills/sci-figures/examples/fig1_moscot.py` writes
77
+ `figures/fig1_moscot.pdf`, its legend and preview (needs TeX). The spatial one needs the `spatial-examples` extra and the
78
+ Xenium dataset (`fig2_spatial_outline.md`, Source): run `fig2_spatial_data.py` (about 7 min on 8 cores), then
79
+ `fig2_spatial.py`.
80
+
81
+ For live package edits in a figure repo, depend on the checkout instead:
82
+ `sci-figures = { path = "../sci-figures", editable = true }`.
83
+
84
+ ## Release
85
+
86
+ Bump `version` in `.claude-plugin/plugin.json` and merge: the marketplace follows `main`, and users update when the
87
+ version changes. On that merge, `release.yaml` publishes the package to PyPI as `sci-figures`, then tags `v<version>` and
88
+ creates a GitHub Release.
89
+
90
+ ## License
91
+
92
+ MIT
@@ -0,0 +1,10 @@
1
+ scifig/__init__.py,sha256=du0CVTroZMT3t-4q3FqgMmpH7qtJtDE2sT8vlUlELC4,677
2
+ scifig/elements.py,sha256=gPlC_D7IJ-ZHPzHAjWgY3IBatfpWQX2nJzR3vQAJoxM,8588
3
+ scifig/export.py,sha256=V7jXQf7nrtlkXoXlOMjbtCWhHjGMXzNa62hQrbXJlmI,3292
4
+ scifig/fonts.py,sha256=_IY4DMfw-IrOzzEQ6hSl6PLIk9w66nzBqGlO_THVl64,1779
5
+ scifig/layout.py,sha256=1O8QAq3RWPoYLZabJTytBp6LidhFQeIQWcV66MEKSOI,2017
6
+ scifig/style.py,sha256=ByyIF03c1JOyyTxBrdrs9zQZ646fS2YiVU3CxufNYFg,6379
7
+ sci_figures-0.3.0.dist-info/METADATA,sha256=7hq6gvRN2LcC46WtvB97LdhBpzMU2PquhsW82Q85IGU,4335
8
+ sci_figures-0.3.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ sci_figures-0.3.0.dist-info/licenses/LICENSE,sha256=4lkOIPKRK48xHbM2EZ3oKqWQ584xZMnfThy0iMECQv0,1064
10
+ sci_figures-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 quadbio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
scifig/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ """scifig: style, mm layout, recurring elements and export for Nature-style research figures."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ from .elements import BadgeHandle, badge, badge_handle, colorbar, embedding_axes, ink_on, scale_bar
6
+ from .export import save
7
+ from .layout import MM, add_axes_mm, new_figure, panel_letter
8
+ from .style import LINEWIDTHS, SIZES, apply_style
9
+
10
+ __all__ = [
11
+ "BadgeHandle",
12
+ "LINEWIDTHS",
13
+ "MM",
14
+ "SIZES",
15
+ "add_axes_mm",
16
+ "apply_style",
17
+ "badge",
18
+ "badge_handle",
19
+ "colorbar",
20
+ "embedding_axes",
21
+ "ink_on",
22
+ "new_figure",
23
+ "panel_letter",
24
+ "save",
25
+ "scale_bar",
26
+ ]
27
+ __version__ = version("sci-figures")
scifig/elements.py ADDED
@@ -0,0 +1,216 @@
1
+ """Recurring visual elements: embedding axis arrows, end-labelled colorbars, scale bars, badges and badge keys."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from matplotlib.axes import Axes
6
+ from matplotlib.colorbar import Colorbar
7
+ from matplotlib.colors import to_rgb
8
+ from matplotlib.font_manager import FontProperties
9
+ from matplotlib.legend import Legend
10
+ from matplotlib.legend_handler import HandlerBase
11
+ from matplotlib.lines import Line2D
12
+ from matplotlib.markers import MarkerStyle
13
+ from matplotlib.text import Text
14
+ from matplotlib.textpath import TextPath
15
+
16
+ from .layout import MM, _size_mm
17
+ from .style import LINEWIDTHS, SIZES
18
+
19
+
20
+ def embedding_axes(ax: Axes, basis: str = "UMAP", arrow_mm: float = 5.0) -> None:
21
+ """Replace frame and ticks with an L-shaped indicator labelled ``basis``1/2 at the bottom-left.
22
+
23
+ Fits the view to the data so the indicator sits at the scatter's corner. Call after plotting.
24
+ """
25
+ ax.margins(0.02)
26
+ ax.set_xticks([])
27
+ ax.set_yticks([])
28
+ ax.set_xlabel("")
29
+ ax.set_ylabel("")
30
+ for s in ax.spines.values():
31
+ s.set_visible(False)
32
+ fw, fh = _size_mm(ax.figure)
33
+ w_mm, h_mm = ax.get_position().width * fw, ax.get_position().height * fh
34
+ arrow = {
35
+ "arrowstyle": "-|>,head_length=0.25,head_width=0.12",
36
+ "lw": LINEWIDTHS["axis"],
37
+ "color": "black",
38
+ "shrinkA": 0,
39
+ "shrinkB": 0,
40
+ }
41
+ kw = {"xycoords": "axes fraction", "textcoords": "axes fraction", "arrowprops": arrow, "annotation_clip": False}
42
+ ax.annotate("", xy=(arrow_mm / w_mm, 0), xytext=(0, 0), **kw)
43
+ ax.annotate("", xy=(0, arrow_mm / h_mm), xytext=(0, 0), **kw)
44
+ t = {"fontsize": SIZES["text"], "transform": ax.transAxes, "clip_on": False}
45
+ ax.text(0, -0.8 / h_mm, f"{basis}1", ha="left", va="top", **t)
46
+ ax.text(-0.8 / w_mm, 0, f"{basis}2", ha="right", va="bottom", rotation=90, **t)
47
+
48
+
49
+ def colorbar(
50
+ mappable,
51
+ cax: Axes,
52
+ label: str | None = None,
53
+ ends: tuple[str, str] | None = ("Low", "High"),
54
+ orientation: str = "vertical",
55
+ ) -> Colorbar:
56
+ """Thin colorbar in ``cax`` (e.g. 1.5 x 12 mm), ticked at its ends only.
57
+
58
+ ``ends`` replaces the end labels; ``None`` keeps the numbers (set vmin/vmax so they are
59
+ exact). ``label`` sits above the bar, flush with its left edge. Horizontal end labels align
60
+ inwards, so nothing overhangs the bar.
61
+ """
62
+ cb = cax.figure.colorbar(mappable, cax=cax, orientation=orientation)
63
+ cb.outline.set_visible(False)
64
+ cb.set_ticks([mappable.norm.vmin, mappable.norm.vmax])
65
+ if ends is not None:
66
+ cb.set_ticklabels(list(ends))
67
+ cb.ax.tick_params(length=0, pad=1, labelsize=SIZES["text"])
68
+ if orientation == "horizontal":
69
+ lo, hi = cb.ax.get_xticklabels()
70
+ lo.set_horizontalalignment("left")
71
+ hi.set_horizontalalignment("right")
72
+ if label:
73
+ cax.set_title(label, loc="left", fontsize=SIZES["text"], pad=SIZES["text"] * 0.6 + 2)
74
+ return cb
75
+
76
+
77
+ def scale_bar(
78
+ ax: Axes, length: float, unit: str = "µm", data_unit_size: float = 1.0, loc: str = "lower right", **kwargs
79
+ ):
80
+ """Scale bar of ``length`` ``unit``, drawn in ``ax``'s data coordinates so it survives layout changes.
81
+
82
+ ``data_unit_size`` is the size of one data unit in ``unit`` (e.g. µm per pixel). Other
83
+ keyword arguments go to ``AnchoredSizeBar`` (e.g. ``bbox_to_anchor`` to place it outside
84
+ the image). ``save`` reports its length on the page.
85
+ """
86
+ from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
87
+
88
+ kw = {"pad": 0.5, "sep": 2.0, "frameon": False, "size_vertical": 0, "fontproperties": {"size": SIZES["text"]}}
89
+ kw |= kwargs
90
+ bar = AnchoredSizeBar(ax.transData, length / data_unit_size, f"{length:g} {unit}", loc, **kw)
91
+ bar.size_bar.get_children()[0].set_linewidth(LINEWIDTHS["data"])
92
+ bar._scifig = {"length": length, "unit": unit, "data_length": length / data_unit_size}
93
+ ax.add_artist(bar)
94
+ return bar
95
+
96
+
97
+ def ink_on(color) -> str:
98
+ """Black or white, whichever reads on ``color``: black above WCAG relative luminance 0.179."""
99
+ r, g, b = (v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4 for v in to_rgb(color))
100
+ return "black" if 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.179 else "white"
101
+
102
+
103
+ def _filled(marker: str) -> MarkerStyle:
104
+ style = MarkerStyle(marker)
105
+ if not style.is_filled():
106
+ raise ValueError(f"A badge is a filled shape; {marker!r} is a line marker.")
107
+ return style
108
+
109
+
110
+ def badge(
111
+ ax: Axes,
112
+ x: float,
113
+ y: float,
114
+ color,
115
+ id: str | int | None = None,
116
+ diameter: float = 3.0,
117
+ transform=None,
118
+ marker: str = "o",
119
+ fontsize: float | None = None,
120
+ edgecolor=None,
121
+ ):
122
+ """An entity's mark: a filled shape (``diameter`` mm) with an optional centred ID.
123
+
124
+ The ID is ``fontsize`` pt (default ``SIZES["min"]``), black or white by contrast (`ink_on`).
125
+ ``edgecolor`` outlines the shape, e.g. over points of its own color. ``transform`` defaults to
126
+ data coordinates; axes or blended transforms (``ax.get_yaxis_transform()``) place a badge
127
+ beside the data. Returns ``(marker, text)``.
128
+
129
+ ``marker`` is a filled matplotlib marker, so different kinds of entity can carry different
130
+ shapes. At one ``diameter``, a diamond (``"D"``) leaves the ID as much room as a circle
131
+ (equal inscribed square) but its tips reach 1.41x further; space neighbouring badges for that.
132
+ """
133
+ _filled(marker)
134
+ transform = transform or ax.transData
135
+ (marker,) = ax.plot(
136
+ [x],
137
+ [y],
138
+ marker=marker,
139
+ ls="",
140
+ markersize=diameter * MM * 72,
141
+ markerfacecolor=color,
142
+ markeredgecolor="none" if edgecolor is None else edgecolor,
143
+ markeredgewidth=LINEWIDTHS["axis"],
144
+ transform=transform,
145
+ clip_on=False,
146
+ scalex=False,
147
+ scaley=False,
148
+ )
149
+ text = None
150
+ if id is not None:
151
+ text = ax.text(
152
+ x,
153
+ y,
154
+ str(id),
155
+ transform=transform,
156
+ ha="center",
157
+ va="center_baseline",
158
+ fontsize=SIZES["min"] if fontsize is None else fontsize,
159
+ color=ink_on(color),
160
+ clip_on=False,
161
+ )
162
+ return marker, text
163
+
164
+
165
+ class BadgeHandle:
166
+ """A legend entry drawn as a badge; make one with `badge_handle`."""
167
+
168
+ def __init__(self, color, id=None, marker="o", edgecolor=None, label=""):
169
+ _filled(marker)
170
+ self.color, self.id, self.marker, self.edgecolor, self.label = color, id, marker, edgecolor, label
171
+
172
+ def get_label(self) -> str:
173
+ """The legend's text for this entry."""
174
+ return self.label
175
+
176
+
177
+ def badge_handle(color, id: str | int | None = None, *, marker: str = "o", label: str = "", edgecolor=None):
178
+ """Legend handle for `badge`'s mark: ``ax.legend(handles=[sf.badge_handle(color, id="5", label="Forebrain")])``.
179
+
180
+ The badge fills the legend's handle box (``handleheight`` and ``handlelength``; matplotlib
181
+ takes a descent off the height). The ID takes the legend's font size, shrunk only where two
182
+ digits would not fit the badge; at ``handleheight=2`` and above they fit.
183
+ """
184
+ return BadgeHandle(color, id, marker, edgecolor, label)
185
+
186
+
187
+ class _HandlerBadge(HandlerBase):
188
+ def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans):
189
+ h = orig_handle
190
+ style = _filled(h.marker)
191
+ extent = style.get_path().transformed(style.get_transform()).get_extents()
192
+ edge = 0 if h.edgecolor is None else LINEWIDTHS["axis"]
193
+ size = (min(width, height) - edge) / max(extent.width, extent.height) # markersize, pt
194
+ centre = (width / 2 - xdescent, height / 2 - ydescent)
195
+ mark = Line2D(
196
+ [centre[0]],
197
+ [centre[1]],
198
+ marker=h.marker,
199
+ ls="",
200
+ markersize=size,
201
+ markerfacecolor=h.color,
202
+ markeredgecolor="none" if h.edgecolor is None else h.edgecolor,
203
+ markeredgewidth=LINEWIDTHS["axis"],
204
+ transform=trans,
205
+ )
206
+ if h.id is None:
207
+ return [mark]
208
+ # The ID's room is the square inscribed in a circle of the markersize, as in `badge`.
209
+ ink = TextPath((0, 0), "00", prop=FontProperties(size=fontsize)).get_extents()
210
+ idsize = min(fontsize, fontsize * size / 2**0.5 / max(ink.width, ink.height))
211
+ text = Text(*centre, str(h.id), ha="center", va="center_baseline", fontsize=idsize, color=ink_on(h.color))
212
+ text.set_transform(trans)
213
+ return [mark, text]
214
+
215
+
216
+ Legend.update_default_handler_map({BadgeHandle: _HandlerBadge()})
scifig/export.py ADDED
@@ -0,0 +1,74 @@
1
+ """Export: one PDF per figure with editable Arial text, plus a PNG preview."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import shutil
7
+ from pathlib import Path
8
+
9
+ import matplotlib as mpl
10
+ from matplotlib.figure import Figure
11
+
12
+ from .layout import MM, _size_mm
13
+ from .style import FONT, RASTER_DPI
14
+
15
+ MAX_PDF_MB = 5.0
16
+ DPI_STEPS = (RASTER_DPI, 900, 600, 450, 300) # tried in order; 300 is Nature's minimum
17
+
18
+
19
+ def _scale_bars(fig: Figure) -> list[str]:
20
+ """Page length of each ``scale_bar``; raises if its axes scale x and y differently."""
21
+ fig.canvas.draw() # equal aspect resizes axes at draw time
22
+ out = []
23
+ for ax in fig.axes:
24
+ for bar in ax.artists:
25
+ meta = getattr(bar, "_scifig", None)
26
+ if meta is None:
27
+ continue
28
+ o, x1, y1 = ax.transData.transform([(0, 0), (1, 0), (0, 1)])
29
+ mm_x, mm_y = abs(x1[0] - o[0]) / fig.dpi / MM, abs(y1[1] - o[1]) / fig.dpi / MM
30
+ if abs(mm_x - mm_y) > 0.01 * max(mm_x, mm_y):
31
+ raise ValueError(
32
+ f"Scale bar {meta['length']:g} {meta['unit']}: x and y scales differ; set ax.set_aspect('equal')."
33
+ )
34
+ out.append(
35
+ f"Scale bar {meta['length']:g} {meta['unit']} = {meta['data_length'] * mm_x:.2f} mm on the page."
36
+ )
37
+ return out
38
+
39
+
40
+ def save(fig: Figure, path: str | Path, legend: str | Path | None = None, dpi: int | None = None) -> Path:
41
+ """Write ``path`` as PDF and ``<dir>/.preview/<name>.png``; print size, raster dpi and scale bars.
42
+
43
+ Rasters are written at the first of ``DPI_STEPS`` that keeps the PDF within ``MAX_PDF_MB``
44
+ (or at ``dpi``). Raises if the PDF holds fonts other than Arial or Type 3 fonts, which are
45
+ not editable. ``legend``, the legend kept with the script, is copied next to the PDF as
46
+ ``<name>_legend.md``.
47
+ """
48
+ path = Path(path).with_suffix(".pdf")
49
+ path.parent.mkdir(parents=True, exist_ok=True)
50
+ if legend is not None:
51
+ dest = path.with_name(f"{path.stem}_legend.md")
52
+ if Path(legend).resolve() != dest.resolve():
53
+ shutil.copyfile(legend, dest)
54
+ report = _scale_bars(fig)
55
+ for d in [dpi] if dpi else DPI_STEPS:
56
+ with mpl.rc_context({"pdf.use14corefonts": False}): # so Type 1 fonts can only come from LaTeX
57
+ fig.savefig(path, dpi=d)
58
+ mb = path.stat().st_size / 1e6
59
+ if mb <= MAX_PDF_MB:
60
+ break
61
+ raw = path.read_bytes()
62
+ # Type 1 fonts come only from LaTeX equations (usetex=True); all other text must be Arial.
63
+ fonts = re.findall(rb"/Subtype\s*/(?!Type1\b)\w+\s*/BaseFont\s*/([\w+\-,]+)", raw)
64
+ fonts = {f.decode(errors="ignore") for f in fonts}
65
+ if re.search(rb"/Subtype\s*/Type3", raw) or any(FONT not in f for f in fonts):
66
+ raise ValueError(f"{path.name} embeds non-editable or non-{FONT} fonts: {sorted(fonts)}.")
67
+ w, h = _size_mm(fig)
68
+ print(f"{path.name}: {w:.0f} x {h:.0f} mm, {mb:.2f} MB, rasters at {d} dpi.", *report, sep="\n")
69
+ if mb > MAX_PDF_MB:
70
+ print(f"Above {MAX_PDF_MB:g} MB: rasterize dense scatters, subsample points or use smaller markers.")
71
+ preview = path.parent / ".preview" / f"{path.stem}.png"
72
+ preview.parent.mkdir(exist_ok=True)
73
+ fig.savefig(preview, dpi=300)
74
+ return path
scifig/fonts.py ADDED
@@ -0,0 +1,50 @@
1
+ """Install Arial for matplotlib without system privileges.
2
+
3
+ Usage (once per machine):
4
+ python -m scifig.fonts # installs into ~/.local/share/fonts
5
+ python -m scifig.fonts --dir DIR # custom location; then set SCIFIG_FONT_DIR=DIR
6
+
7
+ In pixi environments ``pixi add mscorefonts`` works as well; ``apply_style`` finds either. Arial is
8
+ Microsoft's, under its own license; this fetches conda-forge's ``mscorefonts`` package.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import io
15
+ import tarfile
16
+ import urllib.request
17
+ from pathlib import Path
18
+
19
+ # Microsoft core fonts as packaged on conda-forge (noarch).
20
+ URL = "https://api.anaconda.org/download/conda-forge/mscorefonts/0.0.1/noarch/mscorefonts-0.0.1-3.tar.bz2"
21
+
22
+
23
+ def install(target: str | Path = "~/.local/share/fonts") -> list[Path]:
24
+ """Download the package and extract Arial (regular, bold, italic, bold italic)."""
25
+ target = Path(target).expanduser()
26
+ target.mkdir(parents=True, exist_ok=True)
27
+ with urllib.request.urlopen(URL) as r:
28
+ data = r.read()
29
+ out = []
30
+ with tarfile.open(fileobj=io.BytesIO(data), mode="r:bz2") as tar:
31
+ for m in tar.getmembers():
32
+ name = Path(m.name).name
33
+ if name.lower() in {"arial.ttf", "arialbd.ttf", "ariali.ttf", "arialbi.ttf"}:
34
+ dest = target / name
35
+ dest.write_bytes(tar.extractfile(m).read())
36
+ out.append(dest)
37
+ return out
38
+
39
+
40
+ def main() -> None:
41
+ """Install Arial from the command line."""
42
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
43
+ parser.add_argument("--dir", default="~/.local/share/fonts")
44
+ args = parser.parse_args()
45
+ for p in install(args.dir):
46
+ print(f"installed {p}")
47
+
48
+
49
+ if __name__ == "__main__":
50
+ main()
scifig/layout.py ADDED
@@ -0,0 +1,59 @@
1
+ """Figure canvas and axes in millimetres, panel letters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+
7
+ import matplotlib.pyplot as plt
8
+ from matplotlib.axes import Axes
9
+ from matplotlib.figure import Figure
10
+ from matplotlib.text import Annotation, Text
11
+ from matplotlib.transforms import Bbox
12
+
13
+ from .style import SIZES
14
+
15
+ MM = 1 / 25.4 # inches per mm
16
+
17
+
18
+ def new_figure(width: float, height: float) -> Figure:
19
+ """Figure of exact size in mm."""
20
+ return plt.figure(figsize=(width * MM, height * MM))
21
+
22
+
23
+ def _size_mm(fig: Figure) -> tuple[float, float]:
24
+ w, h = fig.get_size_inches()
25
+ return w / MM, h / MM
26
+
27
+
28
+ def add_axes_mm(fig: Figure, left: float, top: float, width: float, height: float, **kwargs) -> Axes:
29
+ """Axes box (spines, not tick labels) at an exact position in mm from the figure's top-left corner."""
30
+ fw, fh = _size_mm(fig)
31
+ return fig.add_axes((left / fw, 1 - (top + height) / fh, width / fw, height / fh), **kwargs)
32
+
33
+
34
+ def panel_letter(
35
+ fig: Figure,
36
+ letter: str,
37
+ left: float,
38
+ top: float,
39
+ title: str | None = None,
40
+ over: Axes | Sequence[Axes] | None = None,
41
+ ) -> Text:
42
+ """Bold 8 pt panel letter with its top-left corner at ``left, top`` (mm).
43
+
44
+ An optional panel title sits on its line, centered over the axes ``over`` (the plot or plots it titles).
45
+ """
46
+ fw, fh = _size_mm(fig)
47
+ t = fig.text(left / fw, 1 - top / fh, letter, fontsize=SIZES["panel"], fontweight="bold", ha="left", va="top")
48
+ if title:
49
+ if over is None:
50
+ raise ValueError("A panel title is centered over its plot: pass the axes it titles as `over`.")
51
+ axes = [over] if isinstance(over, Axes) else list(over)
52
+
53
+ def span(renderer): # at draw time, since equal aspect resizes axes
54
+ return Bbox.union([a.get_window_extent(renderer) for a in axes])
55
+
56
+ fig.add_artist(
57
+ Annotation(title, xy=(0.5, 0), xycoords=(span, t), ha="center", va="bottom", fontsize=SIZES["text"])
58
+ )
59
+ return t
scifig/style.py ADDED
@@ -0,0 +1,179 @@
1
+ """Global matplotlib style for Nature-style research figures."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import matplotlib as mpl
10
+ from cycler import cycler
11
+ from matplotlib import font_manager
12
+
13
+ FONT = "Arial"
14
+
15
+ # Font sizes in pt (Nature): all text 7 pt, never below 5 pt; panel letters 8 pt bold.
16
+ SIZES = {"text": 7, "min": 5, "panel": 8}
17
+
18
+ # Line widths in pt: minor ticks and patch edges; axes, ticks, error bars and box plots; data lines.
19
+ LINEWIDTHS = {"thin": 0.25, "axis": 0.5, "data": 1.0}
20
+
21
+ # Rasterized parts: 1200 dpi stays sharp at 4x enlargement in Illustrator.
22
+ RASTER_DPI = 1200
23
+
24
+ # scanpy's default categorical palette (scanpy.plotting.palettes.default_20, BSD-3-Clause),
25
+ # used as the color cycle so plain matplotlib plots match scanpy's category colors.
26
+ DEFAULT_20 = [
27
+ "#1f77b4",
28
+ "#ff7f0e",
29
+ "#279e68",
30
+ "#d62728",
31
+ "#aa40fc",
32
+ "#8c564b",
33
+ "#e377c2",
34
+ "#b5bd61",
35
+ "#17becf",
36
+ "#aec7e8",
37
+ "#ffbb78",
38
+ "#98df8a",
39
+ "#ff9896",
40
+ "#c5b0d5",
41
+ "#c49c94",
42
+ "#f7b6d2",
43
+ "#dbdb8d",
44
+ "#9edae5",
45
+ "#ad494a",
46
+ "#8c6d31",
47
+ ]
48
+
49
+
50
+ def _font_dirs() -> list[Path]:
51
+ """Directories that may contain Arial, most specific first."""
52
+ dirs = []
53
+ for var in ("SCIFIG_FONT_DIR", "CONDA_PREFIX", "PIXI_ENVIRONMENT_PREFIX"):
54
+ val = os.environ.get(var)
55
+ if val:
56
+ p = Path(val)
57
+ dirs += [p, p / "fonts"]
58
+ dirs += [Path(sys.prefix) / "fonts", Path.home() / ".local/share/fonts", Path.home() / ".fonts"]
59
+ return [d for d in dirs if d.is_dir()]
60
+
61
+
62
+ def register_fonts() -> bool:
63
+ """Register Arial from the active environment (e.g. conda-forge ``mscorefonts``).
64
+
65
+ Returns True if Arial is available afterwards.
66
+ """
67
+ known = {Path(f.fname).resolve() for f in font_manager.fontManager.ttflist}
68
+ for d in _font_dirs():
69
+ for f in d.glob("[Aa]rial*.ttf"):
70
+ if f.resolve() not in known:
71
+ font_manager.fontManager.addfont(str(f))
72
+ return any(f.name == FONT for f in font_manager.fontManager.ttflist)
73
+
74
+
75
+ def apply_style(strict: bool = True) -> None:
76
+ """Apply the figure style. Call once after importing scanpy and before plotting.
77
+
78
+ Parameters
79
+ ----------
80
+ strict
81
+ Raise if Arial is not available. Never set to False for figures that leave your machine.
82
+ """
83
+ if not register_fonts():
84
+ msg = (
85
+ f"Font '{FONT}' not found. Run `python -m scifig.fonts` once (installs into "
86
+ "~/.local/share/fonts), or `pixi add mscorefonts` in a pixi environment."
87
+ )
88
+ if strict:
89
+ raise RuntimeError(msg)
90
+ print(f"WARNING: {msg}", file=sys.stderr)
91
+
92
+ n = SIZES["text"]
93
+ lw = LINEWIDTHS
94
+ mpl.rcParams.update(
95
+ {
96
+ # fonts and editable text
97
+ "font.family": "sans-serif",
98
+ "font.sans-serif": [FONT, "Helvetica", "DejaVu Sans"],
99
+ "font.size": n,
100
+ "pdf.fonttype": 42,
101
+ "ps.fonttype": 42,
102
+ "svg.fonttype": "none",
103
+ "mathtext.fontset": "custom",
104
+ "mathtext.rm": FONT,
105
+ "mathtext.it": f"{FONT}:italic",
106
+ "mathtext.bf": f"{FONT}:bold",
107
+ "mathtext.sf": FONT,
108
+ "mathtext.cal": FONT, # default 'cursive' is missing on Linux servers
109
+ "mathtext.default": "regular",
110
+ # equations (usetex=True on their text only): Helvetica (matches Arial), sans-serif math
111
+ "text.latex.preamble": r"\usepackage{amsmath}\usepackage[T1]{fontenc}\usepackage{newtxsf}"
112
+ r"\DeclareSymbolFont{operators}{T1}{phv}{m}{n}\DeclareMathAlphabet{\mathrm}{T1}{phv}{m}{n}"
113
+ # math comma and period from Helvetica: recent newtx virtual fonts break matplotlib's dvi reader
114
+ r"\DeclareMathSymbol{,}{\mathpunct}{operators}{`,}\DeclareMathSymbol{.}{\mathord}{operators}{`.}",
115
+ # sizes
116
+ "axes.titlesize": n,
117
+ "axes.titleweight": "normal",
118
+ "axes.titlepad": 3,
119
+ "axes.labelsize": n,
120
+ "axes.labelpad": 2,
121
+ "xtick.labelsize": n,
122
+ "ytick.labelsize": n,
123
+ "legend.fontsize": n,
124
+ "legend.title_fontsize": n,
125
+ "figure.titlesize": n,
126
+ # axes
127
+ "axes.linewidth": lw["axis"],
128
+ "axes.spines.top": False,
129
+ "axes.spines.right": False,
130
+ "axes.grid": False,
131
+ "axes.facecolor": "none",
132
+ "axes.edgecolor": "black",
133
+ "axes.labelcolor": "black",
134
+ "axes.prop_cycle": cycler(color=DEFAULT_20),
135
+ "axes.unicode_minus": True,
136
+ "xtick.direction": "out",
137
+ "ytick.direction": "out",
138
+ "xtick.major.width": lw["axis"],
139
+ "ytick.major.width": lw["axis"],
140
+ "xtick.minor.width": lw["thin"],
141
+ "ytick.minor.width": lw["thin"],
142
+ "xtick.major.size": 2,
143
+ "ytick.major.size": 2,
144
+ "xtick.minor.size": 1,
145
+ "ytick.minor.size": 1,
146
+ "xtick.major.pad": 1.5,
147
+ "ytick.major.pad": 1.5,
148
+ # marks
149
+ "lines.linewidth": lw["data"],
150
+ "lines.markersize": 3,
151
+ "patch.linewidth": lw["thin"],
152
+ "errorbar.capsize": 0,
153
+ "boxplot.flierprops.markersize": 1.5,
154
+ "boxplot.boxprops.linewidth": lw["axis"],
155
+ "boxplot.whiskerprops.linewidth": lw["axis"],
156
+ "boxplot.capprops.linewidth": lw["axis"],
157
+ "boxplot.medianprops.linewidth": lw["axis"],
158
+ "boxplot.medianprops.color": "black",
159
+ "image.cmap": "viridis",
160
+ "scatter.edgecolors": "none",
161
+ # legends
162
+ "legend.frameon": False,
163
+ "legend.borderaxespad": 0.2,
164
+ "legend.borderpad": 0.2,
165
+ "legend.handlelength": 1.0,
166
+ "legend.handleheight": 0.7,
167
+ "legend.handletextpad": 0.4,
168
+ "legend.labelspacing": 0.25,
169
+ "legend.columnspacing": 0.8,
170
+ "legend.markerscale": 1.0,
171
+ # output: exact figure size, raster parts at RASTER_DPI
172
+ "figure.dpi": 150,
173
+ "figure.facecolor": "white",
174
+ "savefig.dpi": RASTER_DPI,
175
+ "savefig.bbox": None,
176
+ "savefig.pad_inches": 0,
177
+ "savefig.facecolor": "white",
178
+ }
179
+ )