X-bar and R Control Limits Python Script Generator
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.
Fill in
See the constants table
xbar_r.py
import csv
import statistics
N = 5
A2 = 0.577
D3 = 0
D4 = 2.114
D2 = 2.326
USL = 25.05
LSL = 24.95
values = []
with open("bore_diameter.csv", newline="") as f:
for row in csv.DictReader(f):
values.append(float(row["diameter"]))
# 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)
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))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.
Feed ERP inspection data into SPC
An optional review of automating measurement data flow from your ERP or MES to charts.
Optional. The tool and every export work without this. No spam.
How to use the generator
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
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
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
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.
Frequently Asked Questions
Does the script need any Python packages?
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?
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?
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?
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.
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.
Related Tools
SPC Control Chart Constants Table (A2, D3, D4, d2)
Lookup table of X-bar and R chart constants for subgroup sizes 2 to 10, with the formulas for centre lines and control limits.
Quality & InspectionPPAP Initial Process Study Ppk Calculator
Enter spec limits, mean and overall standard deviation from your initial process study to get Pp, Ppk, expected PPM and the sigma reduction needed to hit your target.
Developer ToolsPPAP Status Tracker SQL Query Generator
Fill in your table and column names and get SQL queries for overdue, pending and rejected PPAP submissions by supplier.
Quality & InspectionPPAP 18 Elements Reference Table
Searchable table of the 18 PPAP elements, the evidence a customer expects for each, and the common reasons submissions get rejected.
More Developer Tools tools
See all- Automotive EDI 830 Planning Schedule Skeleton Generator
- Warranty Claims Pareto and Months in Service SQL Query Generator
- SAP Sales Order ABAP SELECT Generator (VBAK, VBAP, VBFA)
- SAP Sales Order Create BAPI ABAP Generator (BAPI_SALESORDER_CREATEFROMDAT2)
- SAP ABAP Open Items SELECT Generator
- SAP ACDOCA SQL Query Generator
- SAP QM Inspection Lot ABAP SELECT Generator
- SAP Quality Notification Pareto SQL Query Generator
- SAP QM Usage Decision BAPI Skeleton