1

Ajoute le diagramme de longévité des personnages

This commit is contained in:
2025-12-02 11:01:01 +01:00
parent 4d37a654f2
commit f019deeef5
6 changed files with 210 additions and 4 deletions

View File

@@ -0,0 +1,63 @@
"""Diagramme de longévité des personnages (bornes d'apparition)."""
from pathlib import Path
from typing import List
import matplotlib.pyplot as plt
from lib.filesystem import ensure_parent_dir
from lib.rebrickable.stats import read_rows
def load_spans(path: Path) -> List[dict]:
"""Charge le CSV des bornes min/max par personnage."""
return read_rows(path)
def plot_character_spans(spans_path: Path, destination_path: Path) -> None:
"""Trace un diagramme en barres représentant la longévité des personnages."""
rows = load_spans(spans_path)
if not rows:
return
characters = [row["known_character"] for row in rows]
starts = [int(row["start_year"]) for row in rows]
ends = [int(row["end_year"]) for row in rows]
counts = [int(row["total_minifigs"]) for row in rows]
positions = list(range(len(rows)))
widths = [end - start + 1 for start, end in zip(starts, ends)]
min_year = min(starts)
max_year = max(ends)
height = max(5, len(rows) * 0.3)
fig, ax = plt.subplots(figsize=(12, height))
bars = ax.barh(
positions,
widths,
left=starts,
color="#1f77b4",
edgecolor="#0d0d0d",
linewidth=0.6,
)
ax.set_yticks(positions)
ax.set_yticklabels(characters)
ax.set_xlabel("Années d'apparition")
ax.set_ylabel("Personnage")
ax.set_title("Longévité des personnages (première à dernière apparition)")
ax.set_xlim(min_year - 1, max_year + 1)
ax.grid(True, axis="x", linestyle="--", alpha=0.25)
for bar, start, end, count in zip(bars, starts, ends, counts):
label = f"{start}{end} ({count})" if start != end else f"{start} ({count})"
ax.text(
start + (end - start) / 2,
bar.get_y() + bar.get_height() / 2,
label,
ha="center",
va="center",
fontsize=8,
color="#0d0d0d",
)
ensure_parent_dir(destination_path)
fig.tight_layout()
fig.savefig(destination_path, dpi=160)
plt.close(fig)

View File

@@ -2,7 +2,7 @@
from collections import defaultdict
from pathlib import Path
from typing import Dict, Iterable, List, Sequence
from typing import Dict, Iterable, List, Sequence, Set
from lib.rebrickable.stats import read_rows
from lib.filesystem import ensure_parent_dir
@@ -99,3 +99,55 @@ def write_presence_by_year(path: Path, rows: Sequence[dict]) -> None:
writer.writeheader()
for row in rows:
writer.writerow(row)
def aggregate_character_spans(
minifigs_rows: Iterable[dict],
sets_years: Dict[str, str],
excluded_characters: Sequence[str] | None = None,
) -> List[dict]:
"""Calcule la période d'apparition de chaque personnage (bornes min/max des années observées)."""
excluded = set(excluded_characters or [])
spans: Dict[str, Dict[str, int]] = {}
total_counts: Dict[str, int] = defaultdict(int)
for row in minifigs_rows:
character = row["known_character"].strip()
fig_num = row["fig_num"].strip()
if character == "" or fig_num == "":
continue
if character in excluded:
continue
year = sets_years.get(row["set_num"])
if year is None:
continue
year_int = int(year)
total_counts[character] += 1
current = spans.get(character)
if current is None:
spans[character] = {"start": year_int, "end": year_int}
else:
spans[character]["start"] = min(current["start"], year_int)
spans[character]["end"] = max(current["end"], year_int)
results: List[dict] = []
for character, bounds in spans.items():
results.append(
{
"known_character": character,
"start_year": str(bounds["start"]),
"end_year": str(bounds["end"]),
"total_minifigs": str(total_counts[character]),
}
)
results.sort(key=lambda r: (int(r["start_year"]), int(r["end_year"]), r["known_character"]))
return results
def write_character_spans(path: Path, rows: Sequence[dict]) -> None:
"""Écrit le CSV des bornes min/max par personnage."""
ensure_parent_dir(path)
fieldnames = ["known_character", "start_year", "end_year", "total_minifigs"]
with path.open("w", newline="") as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
for row in rows:
writer.writerow(row)