# X-bar and R Control Limits Python Script Generator

> Source: https://netray.co/tools/xbar-r-control-limits-python-generator
> Publisher: Netray (netray.co), AI and integration engineering for ERP and manufacturing systems.
> Section: Free Tools

## Short answer

Set subgroup size, spec limits and file name and get a short Python script that computes control limits, Cpk and Ppk from CSV data.

## Category

developer

## Industry

Automotive

## Audience

- Quality engineer
- Process engineer
- Data analyst

## Tool

**Kind:** template

**Output:** code

**Language:** python

**Fields:**

#### CSV file name

**Key:** csv_file

**Type:** text

**Default:** bore_diameter.csv

#### Measurement column name

**Key:** column

**Type:** text

**Default:** diameter

#### Subgroup size (2 to 10)

**Key:** n

**Type:** number

**Default:** 5

#### A2 for your n

**Key:** a2

**Type:** number

**Default:** 0.577

**Help:** See the constants table

#### D3 for your n

**Key:** d3

**Type:** number

**Default:** 0

#### D4 for your n

**Key:** d4

**Type:** number

**Default:** 2.114

#### d2 for your n

**Key:** d2

**Type:** number

**Default:** 2.326

#### Upper spec limit

**Key:** usl

**Type:** number

**Default:** 25.05

#### Lower spec limit

**Key:** lsl

**Type:** number

**Default:** 24.95

**Blocks:**

#### xbar_r.py

**Body:** import csv
import statistics

N = {{n}}
A2 = {{a2}}
D3 = {{d3}}
D4 = {{d4}}
D2 = {{d2}}
USL = {{usl}}
LSL = {{lsl}}

values = []
with open("{{csv_file}}", newline="") as f:
    for row in csv.DictReader(f):
        values.append(float(row["{{column}}"]))

# Split into consecutive subgroups of size N, drop the incomplete tail
groups = [values[i:i + N] for i in range(0, len(values) - N + 1, N)]
means = [statistics.mean(g) for g in groups]
ranges = [max(g) - min(g) for g in groups]

grand_mean = statistics.mean(means)
r_bar = statistics.mean(ranges)

print("Subgroups:", len(groups))
print("X-bar chart: CL=%.4f UCL=%.4f LCL=%.4f" % (grand_mean, grand_mean + A2 * r_bar, grand_mean - A2 * r_bar))
print("R chart: CL=%.4f UCL=%.4f LCL=%.4f" % (r_bar, D4 * r_bar, D3 * r_bar))

# Out of control points (rule 1 only)
for i, (m, r) in enumerate(zip(means, ranges), start=1):
    if m > grand_mean + A2 * r_bar or m < grand_mean - A2 * r_bar:
        print("Subgroup %d mean out of limits: %.4f" % (i, m))
    if r > D4 * r_bar or r < D3 * r_bar:
        print("Subgroup %d range out of limits: %.4f" % (i, r))

#### Capability section (append to the script)

**Body:** sigma_within = r_bar / D2
sigma_overall = statistics.stdev(values)

cp = (USL - LSL) / (6 * sigma_within)
cpk = min(USL - grand_mean, grand_mean - LSL) / (3 * sigma_within)
pp = (USL - LSL) / (6 * sigma_overall)
ppk = min(USL - grand_mean, grand_mean - LSL) / (3 * sigma_overall)

print("Cp=%.2f Cpk=%.2f Pp=%.2f Ppk=%.2f" % (cp, cpk, pp, ppk))

**Notes:** Look up A2, D3, D4 and d2 for your subgroup size in the SPC control chart constants table. The script checks only points beyond the limits, not run rules. Only trust capability numbers when the charts show a stable process and the data is roughly normal. Needs Python 3 and no extra packages.

## Content

**Intro:** Many quality engineers still rebuild control limits in a spreadsheet each time. This generator writes a short Python script with the standard library only, which reads a CSV column of measurements and prints X-bar and R chart limits plus Cp, Cpk, Pp and Ppk.

**Sections:**

#### How to use the generator

**Body:** Put your measurements in a CSV with a header and one reading per row in the order they were made. Enter the file name, column and subgroup size, then copy the constants from the SPC constants table for your n. Save the output as xbar_r.py and run it with python. The script splits the data into consecutive subgroups, so order matters.

#### The method behind it

**Body:** Limits use R-bar and the factors A2, D3 and D4 in the standard X-bar and R formulas. Within-subgroup sigma is R-bar divided by d2 and drives Cp and Cpk. Overall sample standard deviation drives Pp and Ppk, the indices PPAP initial studies usually ask for. Many customers want Ppk of at least 1.67 on special characteristics, but follow your customer's stated criteria.

#### Reading the output

**Body:** If any subgroup is listed out of limits, find the cause before trusting capability figures. A large gap between Cpk and Ppk means there is variation between subgroups, such as tool wear or shift change, that the short-term sigma hides. Plot the data as well; numbers alone can miss trends and patterns.

#### Common mistakes

**Body:** Do not mix parts from different cavities or machines in one subgroup unless that is intended. Do not reuse limits from an earlier run without recalculating. Make sure the CSV has no blank lines or text values in the measurement column, or float conversion will fail.

**Cta:** If inspection results are in your ERP, MES or QMS database, we can help feed them directly into charts without CSV exports. Tell us what system you use.

**Faq:**

#### Does the script need any Python packages?

**Answer:** No. It uses only csv and statistics from the Python 3 standard library, so it runs anywhere Python 3 is installed. For plotting you can add matplotlib later, but it is not required for limits and indices.

#### Why does Cpk differ from Ppk?

**Answer:** Cpk uses within-subgroup sigma estimated from the average range, while Ppk uses the overall standard deviation across all readings. Ppk includes shifts and drifts between subgroups, so it is usually lower for a process that is not perfectly stable.

#### What if I have individual readings, not subgroups?

**Answer:** Use an individuals and moving range chart instead, which has different constants (2.66 times the average moving range for limits). This script is for rational subgroups of 2 to 10 readings.

#### Can the script handle one-sided specifications?

**Answer:** Not as written. For a one-sided tolerance, remove the missing limit and compute only the relevant side of Cpk and Ppk, since Cp and Pp are undefined without both limits.

## Search terms

xbar r chart python, control limits python script, spc python csv, calculate cpk python, ppk calculation python, x bar r chart code, spc script generator, process capability python

---
Talk to an engineer: https://netray.co/contact?intent=erp_ai | Machine catalog: https://netray.co/agent/catalog.json
