Skip to content
v0.1.3latest release121 skills4 categories6 sub-categories247 tested scripts397 reference docsContact us
scripts/plot_chart.py
#!/usr/bin/env python3
"""Render a control chart as a standalone SVG (no plotting libraries needed).

Uses the same inputs and calculations as control_limits.py (shared _spc.py). Variables charts get two
panels (X / X-bar and MR / R / S); attribute charts one panel with stepped limits for varying sample sizes.
Points beyond the control limits are drawn in red; --usl/--lsl add specification lines to the main panel
(dashed) for reference only - never use specification limits as control limits.

Usage:
    python plot_chart.py bore.csv --value diameter --subgroup hour --title "OP20 bore" > bore.svg
    python plot_chart.py rejects.csv --defectives rejects --n inspected > p_chart.svg

Exit codes: 0 SVG written, 2 usage or data error.
"""

import argparse
import sys
from html import escape

from _spc import attributes, beyond, choose, read_rows, subgroups, to_float, variables

W, PH, ML, MR, MT = 860, 230, 70, 90, 30


def panel(series, y0, labels, usl=None, lsl=None):
    name, pts, cl, ucl, lcl = series
    n = len(pts)
    ul = ucl if isinstance(ucl, list) else [ucl] * n
    ll = lcl if isinstance(lcl, list) else [lcl] * n
    vals = [v for v in pts if v is not None] + ul + ll + [x for x in (usl, lsl) if x is not None]
    lo, hi = min(vals), max(vals)
    pad = (hi - lo) * 0.08 or 1
    lo, hi = lo - pad, hi + pad
    X = lambda i: ML + (W - ML - MR) * (i / max(1, n - 1))
    Y = lambda v: y0 + PH - (v - lo) / (hi - lo) * PH
    out = [f'<text x="{ML}" y="{y0 - 8}" class="t">{escape(name)}</text>',
           f'<rect x="{ML}" y="{y0}" width="{W - ML - MR}" height="{PH}" class="frame"/>']

    def step(limit, cls, label):
        d = " ".join(f"{'M' if i == 0 else 'L'}{X(i - 0.5 if i else 0):.1f},{Y(v):.1f} L{X(min(i + 0.5, n - 1)):.1f},{Y(v):.1f}" for i, v in enumerate(limit))
        out.append(f'<path d="{d}" class="{cls}"/>')
        out.append(f'<text x="{W - MR + 6}" y="{Y(limit[-1]) + 4:.1f}" class="lab">{label} {limit[-1]:.6g}</text>')

    step(ul, "lim", "UCL")
    step(ll, "lim", "LCL")
    out.append(f'<line x1="{ML}" x2="{W - MR}" y1="{Y(cl):.1f}" y2="{Y(cl):.1f}" class="cl"/>')
    out.append(f'<text x="{W - MR + 6}" y="{Y(cl) + 4:.1f}" class="lab">CL {cl:.6g}</text>')
    for v, lab in ((usl, "USL"), (lsl, "LSL")):
        if v is not None:
            out.append(f'<line x1="{ML}" x2="{W - MR}" y1="{Y(v):.1f}" y2="{Y(v):.1f}" class="spec"/>')
            out.append(f'<text x="{ML + 4}" y="{Y(v) - 4:.1f}" class="lab">{lab} {v:g}</text>')
    path = [f"{X(i):.1f},{Y(v):.1f}" for i, v in enumerate(pts) if v is not None]
    out.append(f'<polyline points="{" ".join(path)}" class="data"/>')
    bad = set(beyond(series))
    for i, v in enumerate(pts):
        if v is not None:
            out.append(f'<circle cx="{X(i):.1f}" cy="{Y(v):.1f}" r="3.2" class="{"ooc" if i in bad else "pt"}"><title>{escape(labels[i])}: {v:.6g}</title></circle>')
    for i in range(0, n, max(1, n // 12)):
        out.append(f'<text x="{X(i):.1f}" y="{y0 + PH + 14}" class="ax">{escape(labels[i])}</text>')
    return out


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("csv")
    ap.add_argument("--value")
    ap.add_argument("--subgroup")
    ap.add_argument("--size", type=int)
    ap.add_argument("--defectives")
    ap.add_argument("--defects")
    ap.add_argument("--n")
    ap.add_argument("--chart", choices=["imr", "xbar-r", "xbar-s", "p", "np", "c", "u"])
    ap.add_argument("--usl", type=float)
    ap.add_argument("--lsl", type=float)
    ap.add_argument("--title", default="Control chart")
    a = ap.parse_args()
    try:
        rows = read_rows(a.csv)
        if a.defectives or a.defects:
            col = a.defectives or a.defects
            if not a.n:
                raise ValueError("attribute charts need --n")
            counts = [to_float(r[col], col) for r in rows]
            sizes = [to_float(r[a.n], a.n) for r in rows]
            chart = a.chart or choose(None, "defectives" if a.defectives else "defects", len(set(sizes)) > 1)
            res, labels = attributes(counts, sizes, chart), [str(i + 1) for i in range(len(rows))]
        elif a.value:
            groups, labels = subgroups(rows, a.value, a.subgroup, a.size)
            chart = a.chart or choose(len(groups[0]))
            res = variables(groups, chart)
        else:
            raise ValueError("give --value or --defectives/--defects with --n")
    except (OSError, KeyError, ValueError, IndexError) as e:
        print(f"error: {e}", file=sys.stderr)
        return 2
    panels = [res["main"]] + ([res["second"]] if "second" in res else [])
    height = MT + len(panels) * (PH + 50) + 10
    body = []
    for k, s in enumerate(panels):
        body += panel(s, MT + 20 + k * (PH + 50), labels, a.usl if k == 0 else None, a.lsl if k == 0 else None)
    style = (".t{font:600 13px sans-serif;fill:#222}.lab,.ax{font:11px sans-serif;fill:#555}.ax{text-anchor:middle}"
             ".frame{fill:#fff;stroke:#ccc}.lim{fill:none;stroke:#c0392b;stroke-width:1.2}.cl{stroke:#2c7a2c;stroke-width:1.2}"
             ".spec{stroke:#7a5cc0;stroke-dasharray:6 4}.data{fill:none;stroke:#3a6ea5;stroke-width:1.2}"
             ".pt{fill:#3a6ea5}.ooc{fill:#d0021b;stroke:#fff}")
    print(f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{height}" viewBox="0 0 {W} {height}">'
          f'<style>{style}</style><text x="{ML}" y="18" class="t">{escape(a.title)} - {chart.upper()}</text>'
          + "".join(body) + "</svg>")
    return 0


if __name__ == "__main__":
    sys.exit(main())
More in Quality Management & ISO 9001

8d-problem-solving-report-writer

Write and review 8D problem-solving reports for customer complaints and serious nonconformities (automotive and aerospace practice: Ford Global 8D, VDA, GM, Stellantis formats): D0 emergency response, D1 cross-functional team and champion, D2 problem description with 5W2H and is / is-not and no cause in the statement, D3 interim containment within 24 hours with verification and clean point, D4 verified occurrence and escape (non-detection) root causes plus systemic cause, D5 permanent corrective actions for each cause verified before implementation, D6 implementation, validation with production data and removal of containment, D7 PFMEA, control plan and read-across to similar products, D8 closure and recognition. Checks an 8D discipline by discipline for missing content, human-error root causes, missing escape cause or action, late containment and dates out of order.

acceptance-sampling-plan-selector

Select and evaluate acceptance sampling plans for incoming, in-process and final inspection: ANSI/ASQ Z1.4 / ISO 2859-1 single sampling under normal inspection (code letter from lot size and inspection level I, II, III, S-1 to S-4; sample size, Ac and Re from AQL, following the table's arrows to the correct plan; 100% when n reaches the lot size; AQLs above 10 per 100 units), operating characteristic curves (Pa at any quality, producer's quality level, indifference point, LTPD, AOQ and AOQL, binomial or hypergeometric), plans designed from producer and consumer risk, and c = 0 zero-acceptance plans. Covers AQL choice by defect class, switching rules between normal, tightened and reduced inspection, when sampling is not appropriate, and random sampling.

approved-supplier-list-manager

Manage and audit an approved supplier list (ASL) / external provider register for ISO 9001 8.4.1, IATF 16949 8.4 and AS9100 8.4.1: supplier status (approved, conditional, probation, pending, disqualified), scope of approval by commodity and process, risk class, certification and expiry, re-evaluation intervals by risk, conditions with end dates, single-source contingency, approver and customer-directed sources. Audits the list for expired or expiring certificates, overdue re-evaluations, conditional or probation status past its decision date, high-risk suppliers without the required certification, single-source suppliers without backup and missing approvers, and checks purchase orders for suppliers that are off-list, disqualified or pending, or buying outside the approved scope. Covers ERP blocks, PO requirements, off-list and emergency purchases.

apqp-phase-planner

Plan and track Advanced Product Quality Planning (AIAG APQP 3rd edition, IATF 16949) for a new or changed automotive part: back-schedule the five phases (plan and define, product design, process design, product and process validation, launch and feedback) from the start-of-production date by program complexity, with overlap, PPAP lead and safe-launch period; list the deliverables and gate for each phase (DFMEA, DVP&R, feasibility, process flow, PFMEA, control plans, MSA, Ppk, run at rate, PPAP, safe launch, lessons learned); adjust for build-to-print suppliers; flag compressed timelines and late or untracked deliverables against a status list. Covers gate reviews, red/yellow/green status reporting, run at rate and safe-launch exit criteria.

as9100-gap-analyzer

Run an AS9100D / EN 9100:2018 gap analysis for aviation, space and defence suppliers on the requirements added to ISO 9001: on-time delivery and conformity focus, management representative, ethics and human-factors awareness, operational planning and operational risk management, configuration management, product safety, counterfeit-part prevention, special requirements, critical items and key characteristics, external provider register and flow-down, FOD prevention, tooling and NC program control, special process validation, first article inspection (AS9102), traceability, in-service data and nonconforming product control. Generates and scores a worksheet, grades missing core controls as major, and checks invalid n/a claims. Covers AS9101/AS9104, OASIS, AS9102 FAI forms, counterfeit standards (AS5553, AS6174, AS6081), NADCAP and the planned IA9100 transition.

audit-report-writer

Write internal, supplier and pre-certification audit reports with the content ISO 19011:2018 6.5 expects: audit objectives, scope, criteria with revisions, dates, team and auditees, method and sampling statement, specific strengths, findings table and three-part finding details (requirement, evidence, statement), conclusion on the degree of fulfilment of criteria, diverging opinions, follow-up deadlines and distribution. Builds a Markdown report from a JSON audit record, generates the conclusion from the findings (major / minor / none) and flags reports missing required content or findings without clause or evidence. Covers conclusion wording, closing meetings, response expectations and verifying corrective actions.