#!/usr/bin/env python3 """График по двум колонкам CSV.""" from __future__ import annotations import argparse import csv from pathlib import Path import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt def main() -> int: parser = argparse.ArgumentParser(description="График по CSV") parser.add_argument("--input", type=Path, required=True, help="Исходный CSV") parser.add_argument("--x", required=True, help="Колонка X") parser.add_argument("--y", required=True, help="Колонка Y") parser.add_argument("--output", type=Path, default=Path("chart.png"), help="Файл изображения") parser.add_argument("--kind", choices=["line", "bar", "scatter"], default="line", help="Тип графика") parser.add_argument("--title", default="", help="Заголовок") parser.add_argument("--delimiter", default=",", help="Разделитель колонок") parser.add_argument("--force", action="store_true", help="Перезаписать выходной файл") args = parser.parse_args() source = args.input.expanduser().resolve() target = args.output.expanduser().resolve() if not source.is_file(): parser.error(f"Файл не найден: {source}") if source == target: parser.error("Выходной файл не должен совпадать с исходным") if target.exists() and not args.force: parser.error(f"Файл уже существует: {target}. Добавьте --force") if len(args.delimiter) != 1: parser.error("Разделитель должен состоять из одного символа") with source.open("r", encoding="utf-8-sig", newline="") as handle: reader = csv.DictReader(handle, delimiter=args.delimiter) if reader.fieldnames is None: parser.error("Не удалось прочитать заголовок") if args.x not in reader.fieldnames or args.y not in reader.fieldnames: parser.error("Укажите существующие колонки в --x и --y") pairs = [] skipped = 0 for row in reader: raw_y = (row.get(args.y) or "").strip() try: value = float(raw_y.replace(",", ".")) except ValueError: skipped += 1 continue pairs.append(((row.get(args.x) or "").strip(), value)) if not pairs: parser.error("Нет строк с числовым Y") labels = [label for label, _ in pairs] values = [value for _, value in pairs] numeric_x = True try: positions = [float(label.replace(",", ".")) for label in labels] except ValueError: numeric_x = False positions = list(range(len(pairs))) figure, axis = plt.subplots(figsize=(10, 6)) if args.kind == "bar": axis.bar(positions, values, color="#2563eb") if not numeric_x: axis.set_xticks(positions) axis.set_xticklabels(labels, rotation=45, ha="right") elif args.kind == "scatter": axis.scatter(positions, values, color="#2563eb") else: axis.plot(positions, values, marker="o", color="#2563eb") axis.set_title(args.title or f"{args.y} по {args.x}") axis.set_xlabel(args.x) axis.set_ylabel(args.y) axis.grid(True, axis="y", alpha=0.3) figure.tight_layout() target.parent.mkdir(parents=True, exist_ok=True) figure.savefig(target, dpi=150) plt.close(figure) print(f"Точек: {len(pairs)}, пропущено: {skipped}") print(f"Тип: {args.kind}") print(f"Результат: {target}") return 0 if __name__ == "__main__": raise SystemExit(main())