shortstats/src/shortstats/web/transpose.py
ploush 81ef12a9cd
Some checks failed
build / test (push) Failing after 2m48s
build / images (collector) (push) Has been skipped
build / images (web) (push) Has been skipped
upgrade 1.4.0
2026-11-29 20:43:50 +01:00

113 lines
4.9 KiB
Python

"""Axes inversés (1.3.0) : toute donnée en abscisse comme en ordonnée.
Deux choix d'axes n'existent que dans un sens dans les moteurs de diagrammes :
« Nombre de vidéos » (toujours la hauteur des barres) et l'âge, l'étape ou la
date du relevé (toujours l'abscisse de l'évolution). Placés sur l'autre axe, le
diagramme est construit dans le sens habituel (configuration « canonique » :
abscisse et ordonnée échangées), avec ses filtres, zooms, vidéos mises en avant
et légendes, puis le dessin est retourné ici : x et y échangés partout.
Nombre de vidéos en abscisse, thème en ordonnée -> barres horizontales
Vues (toutes les étapes) en abscisse, âge en ordonnée -> courbe verticale
"""
from __future__ import annotations
import dataclasses
from .chart_config import ChartConfig
from .sources import source_of
SWAP = {"x": "y", "y": "x", "x2": "y2", "y2": "x2", "xOffset": "yOffset", "yOffset": "xOffset"}
ORIENT = {"left": "bottom", "right": "top", "bottom": "left", "top": "right"}
# Hauteur d'une catégorie (et d'une barre groupée) quand les catégories passent à la verticale.
ROW = 22
OFFSET_ROW = 14
def is_transposed(cfg: ChartConfig) -> bool:
return source_of(cfg).is_transposed(cfg)
def canonical(cfg: ChartConfig) -> ChartConfig:
"""La configuration dans le sens des moteurs (abscisse et ordonnée échangées si besoin)."""
return dataclasses.replace(cfg, x=cfg.y, y=cfg.x) if is_transposed(cfg) else cfg
def _axis(d: dict, to: str) -> None:
"""Encodage déplacé vers l'axe `to` : orientation de l'axe et titre adaptés."""
axis = d.get("axis")
if not isinstance(axis, dict):
return
if axis.get("orient") in ORIENT:
axis["orient"] = ORIENT[axis["orient"]]
if to == "x":
# titre d'un axe vertical (lu de bas en haut, à droite) : sans objet en bas ou en haut
for k in ("titleAngle", "titleBaseline"):
axis.pop(k, None)
def _node(node: dict) -> None:
enc = node.get("encoding")
if isinstance(enc, dict):
new = {}
for k, v in enc.items():
k2 = SWAP.get(k, k)
if isinstance(v, dict) and k2 in {"x", "y"}:
_axis(v, k2)
if k in {"x", "y"} and isinstance(v, dict) and isinstance(v.get("sort"), str) and v["sort"].lstrip("-") in {"x", "y"}:
v["sort"] = v["sort"].replace(v["sort"].lstrip("-"), SWAP[v["sort"].lstrip("-")])
new[k2] = v
node["encoding"] = new
mark = node.get("mark")
if mark == "line" or (isinstance(mark, dict) and mark.get("type") == "line"):
# le trait relie les points dans l'ordre de l'axe vertical (« horizontal » pour Vega-Lite)
node["mark"] = {**({"type": "line"} if mark == "line" else mark), "orient": "horizontal"}
res = (node.get("resolve") or {}).get("scale")
if isinstance(res, dict):
node["resolve"]["scale"] = {SWAP.get(k, k): v for k, v in res.items()}
for child in node.get("layer", []) or []:
_node(child)
def _vertical_categories(body: dict, rows: list[dict]) -> tuple[int, int]:
"""(catégories, barres par catégorie) sur l'axe vertical après inversion."""
encs = [body.get("encoding") or {}] + [layer.get("encoding") or {} for layer in body.get("layer", []) or []]
for enc in encs:
y = enc.get("y")
if isinstance(y, dict) and y.get("type") in {"nominal", "ordinal"} and "bin" not in y and y.get("field"):
values = {str(r.get(y["field"])) for r in rows if "hl" not in r}
off = enc.get("yOffset")
groups = 1
if isinstance(off, dict) and off.get("field"):
groups = max(1, len({str(r.get(off["field"])) for r in rows if "hl" not in r}))
return len(values), groups
return 0, 1
def _height(n: int, groups: int, current) -> int:
per = ROW if groups <= 1 else OFFSET_ROW * groups + 8
return max(220, min(per * n + 40, 1400))
def apply(result: dict) -> None:
"""Retourne le diagramme construit dans le sens canonique (x et y échangés)."""
spec = result.get("spec")
if spec:
facet = "facet" in spec
body = spec["spec"] if facet else spec
_node(body)
if facet and isinstance((spec.get("resolve") or {}).get("scale"), dict):
spec["resolve"]["scale"] = {SWAP.get(k, k): v for k, v in spec["resolve"]["scale"].items()}
n, groups = _vertical_categories(body, spec.get("data", {}).get("values") or [])
if n:
body["height"] = _height(n, groups, body.get("height"))
resolved = result.get("resolved") or {}
resolved["transposed"] = True
for info in resolved.get("y_axes") or []:
# le curseur de « l'axe vertical » règle maintenant l'axe horizontal
info["orient"] = "horizontal"
if info.get("side"):
info["side"] = {"left": "bottom", "right": "top"}.get(info["side"], info["side"])
if result.get("explanation") is not None and spec:
result["explanation"] += " · axes inversés"