polytope-theme 0.7.2__tar.gz → 0.8.1__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: polytope-theme
3
- Version: 0.7.2
3
+ Version: 0.8.1
4
4
  Summary: Chart and app themes for the Polytope design system: matplotlib, plotly, gradio, streamlit.
5
5
  Project-URL: Homepage, https://github.com/dario-loi/polytope
6
6
  Project-URL: Source, https://github.com/dario-loi/polytope/tree/main/python
@@ -89,6 +89,16 @@ from matplotlib.colors import TwoSlopeNorm
89
89
  ax.imshow(delta, cmap="ply-diverging", norm=TwoSlopeNorm(vcenter=0))
90
90
  ```
91
91
 
92
+ To put a plot in a web page so its colors follow the page's theme, draw it under `ply.use("light")` and save it as inline SVG:
93
+
94
+ ```python
95
+ from polytope_theme.mpl import save_inline_svg
96
+
97
+ save_inline_svg(fig, "plot.svg") # ink becomes currentColor, series become var(--ply-viz-1, ...)
98
+ ```
99
+
100
+ The Astro `PlotSvg` component inlines the file, and the stylesheet sets the series colors for each theme. Text stays text.
101
+
92
102
  To apply the style to one block of code, use `plt.rc_context(polytope_theme.mpl.rc_params("dark"))`.
93
103
 
94
104
  matplotlib only finds Libre Franklin if it is installed as a system font (TTF or OTF from Google Fonts). Without it, text falls back to Franklin Gothic, Helvetica Neue, Arial and then DejaVu Sans.
@@ -57,6 +57,16 @@ from matplotlib.colors import TwoSlopeNorm
57
57
  ax.imshow(delta, cmap="ply-diverging", norm=TwoSlopeNorm(vcenter=0))
58
58
  ```
59
59
 
60
+ To put a plot in a web page so its colors follow the page's theme, draw it under `ply.use("light")` and save it as inline SVG:
61
+
62
+ ```python
63
+ from polytope_theme.mpl import save_inline_svg
64
+
65
+ save_inline_svg(fig, "plot.svg") # ink becomes currentColor, series become var(--ply-viz-1, ...)
66
+ ```
67
+
68
+ The Astro `PlotSvg` component inlines the file, and the stylesheet sets the series colors for each theme. Text stays text.
69
+
60
70
  To apply the style to one block of code, use `plt.rc_context(polytope_theme.mpl.rc_params("dark"))`.
61
71
 
62
72
  matplotlib only finds Libre Franklin if it is installed as a system font (TTF or OTF from Google Fonts). Without it, text falls back to Franklin Gothic, Helvetica Neue, Arial and then DejaVu Sans.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "polytope-theme"
7
- version = "0.7.2"
7
+ version = "0.8.1"
8
8
  description = "Chart and app themes for the Polytope design system: matplotlib, plotly, gradio, streamlit."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -25,7 +25,7 @@ from __future__ import annotations
25
25
 
26
26
  from ._tokens import CATEGORICAL, COLORS, DIVERGING, FONTS, SEQUENTIAL, STATUS, SURFACE
27
27
 
28
- __version__ = "0.7.2"
28
+ __version__ = "0.8.1"
29
29
 
30
30
  __all__ = [
31
31
  "CATEGORICAL",
@@ -13,7 +13,7 @@ import re
13
13
  from pathlib import Path
14
14
  from typing import TYPE_CHECKING, Any, Iterable, Sequence
15
15
 
16
- from ._tokens import DIVERGING, SEQUENTIAL
16
+ from ._tokens import CATEGORICAL, COLORS, DIVERGING, SEQUENTIAL
17
17
 
18
18
  try:
19
19
  import matplotlib as _matplotlib
@@ -24,15 +24,18 @@ except ImportError: # matplotlib is an optional extra
24
24
 
25
25
  if TYPE_CHECKING:
26
26
  from matplotlib.axes import Axes
27
+ from matplotlib.figure import Figure
27
28
  from matplotlib.text import Annotation
28
29
 
29
30
  __all__ = [
30
31
  "DIVERGING_NAME",
31
32
  "SEQUENTIAL_NAME",
32
33
  "diverging_cmap",
34
+ "inline_svg",
33
35
  "label_lines",
34
36
  "rc_params",
35
37
  "register_cmaps",
38
+ "save_inline_svg",
36
39
  "sequential_cmap",
37
40
  "style_path",
38
41
  "use",
@@ -271,5 +274,58 @@ def label_lines(
271
274
  return out
272
275
 
273
276
 
277
+ def inline_svg(fig: "Figure") -> str:
278
+ """Return ``fig`` as an SVG string whose colors follow the page's theme.
279
+
280
+ Draw the figure under ``use("light")``. Its Polytope colors then become CSS, so one
281
+ file serves both themes when it is inlined in a page (the Astro ``PlotSvg`` component
282
+ does that):
283
+
284
+ - the ink color becomes ``currentColor``, so text and strokes take the page's text color;
285
+ - the muted ink, the grid, and the page ground become
286
+ ``var(--ply-color-text-muted, ...)``, ``var(--ply-color-rule, ...)`` and
287
+ ``var(--ply-color-bg, ...)``;
288
+ - the eight categorical colors become ``var(--ply-viz-1, ...)`` to ``var(--ply-viz-8, ...)``,
289
+ which the stylesheet sets for each theme. The original light value is the fallback.
290
+
291
+ Text is kept as text (``svg.fonttype: none``), for readers and crawlers, and the figure
292
+ is saved with a transparent background. The output is repeatable: the same figure gives
293
+ the same string. Colors other than these (a custom color you
294
+ passed to matplotlib) are left as they are.
295
+ """
296
+ _require()
297
+ import io
298
+
299
+ light = COLORS["light"]
300
+ swaps = {
301
+ light["text"].lower(): "currentColor",
302
+ light["text_muted"].lower(): f"var(--ply-color-text-muted, {light['text_muted'].lower()})",
303
+ light["rule"].lower(): f"var(--ply-color-rule, {light['rule'].lower()})",
304
+ light["bg"].lower(): f"var(--ply-color-bg, {light['bg'].lower()})",
305
+ }
306
+ for i, color in enumerate(CATEGORICAL["light"], start=1):
307
+ swaps[color.lower()] = f"var(--ply-viz-{i}, {color.lower()})"
308
+
309
+ buf = io.StringIO()
310
+ # A fixed hash salt and no date make the output repeatable: the same figure gives the same
311
+ # file, so a committed plot changes only when the plot does.
312
+ with _matplotlib.rc_context({"svg.fonttype": "none", "svg.hashsalt": "polytope"}):
313
+ fig.savefig(buf, format="svg", transparent=True, metadata={"Date": None})
314
+ svg = buf.getvalue()
315
+ # matplotlib writes colors as #rrggbb in style declarations; swap each whole token.
316
+ return re.sub(
317
+ r"#[0-9a-fA-F]{6}\b",
318
+ lambda m: swaps.get(m.group(0).lower(), m.group(0)),
319
+ svg,
320
+ )
321
+
322
+
323
+ def save_inline_svg(fig: "Figure", path: str | Path) -> Path:
324
+ """Write ``inline_svg(fig)`` to ``path`` and return the path."""
325
+ out = Path(path)
326
+ out.write_text(inline_svg(fig), encoding="utf-8")
327
+ return out
328
+
329
+
274
330
  if _matplotlib is not None:
275
331
  register_cmaps()
@@ -119,3 +119,19 @@ def test_label_lines_skips_nan_tail():
119
119
  ax.plot([0, 1, 2], [1.0, 2.0, float("nan")], label="a")
120
120
  (ann,) = mpl.label_lines(ax)
121
121
  assert ann.xy == (1.0, 2.0)
122
+
123
+
124
+ def test_inline_svg_follows_the_page_theme(tmp_path):
125
+ dl.use("light")
126
+ fig, ax = plt.subplots()
127
+ ax.plot([0, 1, 2], [1, 3, 2])
128
+ ax.plot([0, 1, 2], [2, 1, 3])
129
+ ax.set_title("A title")
130
+ svg = mpl.inline_svg(fig)
131
+ assert "currentColor" in svg
132
+ assert "var(--ply-viz-1, #d9412b)" in svg
133
+ assert "var(--ply-viz-2, #009b93)" in svg
134
+ assert "<text" in svg # text stays text
135
+ assert "#141414" not in svg.lower()
136
+ out = mpl.save_inline_svg(fig, tmp_path / "plot.svg")
137
+ assert out.read_text(encoding="utf-8") == svg
@@ -8,7 +8,7 @@ HEX = re.compile(r"^#[0-9A-F]{6}$")
8
8
 
9
9
 
10
10
  def test_version():
11
- assert dl.__version__ == "0.7.2"
11
+ assert dl.__version__ == "0.8.1"
12
12
 
13
13
 
14
14
  def test_categorical_shapes():
File without changes
File without changes