Python draws X-bar charts and R charts | Statistical process control SPC

X-bar charts and R charts are two common tools used in statistical process control (SPC) to monitor the mean and range (variability) of a process. These diagrams help identify changes and anomalies in the process so corrective actions can be taken promptly.

**X-bar chart (mean control chart)** shows the average value of a series of samples and is used to monitor whether the average value of the process remains within the acceptable range. X-bar charts usually consist of the following elements:

  1. Sample mean : The average of the data points for each sample, typically used in a per-sample data set.

  2. Centerline : Usually the average of all sample means and represents the target value of the process.

  3. Control limits : usually include upper control limits and lower control limits, used to indicate the acceptable range of process average values. The method of calculating control limits can vary depending on the needs, and common methods include using standard deviation and sample size.

  4. Data Points : The average value of each sample is represented as data points on an X-bar chart, and lines are often used to connect these data points to show trends.

**R Chart (Range Control Chart)** shows the range (the difference between the maximum and minimum values) of a series of samples and is used to monitor the variability of a process. R diagrams usually consist of the following elements:

  1. Range (R) : The difference between the maximum and minimum values ​​of each sample.

  2. Centerline : Typically the average of all R values ​​and represents the variability target for the process.

  3. Control limits : Usually include an upper control limit to indicate the acceptable range of R values. The method of calculating control limits can vary depending on the needs, and common methods include using standard deviation and sample size.

  4. Data Points : The R value for each sample is represented as data points on the R chart, and lines are usually connected to these data points to show trends.

Before drawing X-bar charts and R charts, the following steps need to be performed:

  1. Collect sample data and determine sample size and sampling frequency.

  2. Calculate the mean (X-bar chart) and range (R chart) for each sample.

  3. Calculate center lines and control limits for X-bar charts and R charts.

  4. Draw X-bar plots and R plots and display sample data points along with center lines and control limits.

To generate tabular data and write it to a file, then read the data and calculate the mean, standard deviation, etc. required for X-bar plots and R plots, you can follow the steps below. First, make sure you have NumPy, matplotlib, and Pandas libraries installed.

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

plt.rcParams['font.sans-serif'] = ['SimHei']  # 防止中文标签乱码
plt.rcParams['axes.unicode_minus'] = False

# 生成随机数据,例如,生成5个样本,每个样本5个数据点
data = np.random.rand(5, 5)

# 创建一个Pandas DataFrame
df = pd.DataFrame(data, columns=['Sample 1', 'Sample 2', 'Sample 3', 'Sample 4', 'Sample 5'])

# 将数据写入CSV文件
df.to_csv('sample_data.csv', index=False)

# 从CSV文件读取数据
df = pd.read_csv('sample_data.csv')

# 打印数据框的前几行以确保数据已成功加载
print(df.head())

# 计算每个样本的平均值
x_bar = df.mean(axis=1)

# 计算每个样本的范围(R)
R = df.max(axis=1) - df.min(axis=1)

# 计算平均值和R的平均值
x_bar_avg = x_bar.mean()
R_avg = R.mean()

# 计算X-bar图的控制限(通常为平均值的上下控制限)
x_bar_upper_limit = x_bar_avg + 0.577 * R_avg
x_bar_lower_limit = x_bar_avg - 0.577 * R_avg

# 计算R图的控制限(通常为R的上限)
R_upper_limit = R_avg * 2.114

# 打印计算结果
print(f'X-bar平均值: {x_bar_avg}')
print(f'R平均值: {R_avg}')
print(f'X-bar控制限: ({x_bar_lower_limit}, {x_bar_upper_limit})')
print(f'R控制限: {R_upper_limit}')

# 绘制X-bar图和R图(二行一列)
fig, axes = plt.subplots(2, 1, figsize=(6, 6))  # 创建2行1列的子图
#plt.subplots_adjust(hspace=1)  # 调整垂直间距

# 绘制X-bar图
axes[0].plot(x_bar, marker='o', linestyle='-')
axes[0].axhline(y=x_bar_avg, color='r', linestyle='--', label='平均值')
axes[0].axhline(y=x_bar_upper_limit, color='g', linestyle='--', label='控制限')
axes[0].axhline(y=x_bar_lower_limit, color='g', linestyle='--')
axes[0].set_title('X-bar图')
axes[0].set_xlabel('样本编号')
axes[0].set_ylabel('平均值')
axes[0].legend()
axes[0].grid()

# 绘制R图
axes[1].plot(R, marker='o', linestyle='-')
axes[1].axhline(y=R_avg, color='r', linestyle='--', label='平均值')
axes[1].axhline(y=R_upper_limit, color='g', linestyle='--', label='控制限')
axes[1].set_title('R图')
axes[1].set_xlabel('样本编号')
axes[1].set_ylabel('范围 (R)')
axes[1].legend()
axes[1].grid()

plt.tight_layout()  # 调整子图之间的间距
plt.show()

#    Sample 1  Sample 2  Sample 3  Sample 4  Sample 5
# 0  0.333763  0.887816  0.047209  0.282097  0.285214
# 1  0.215519  0.150961  0.528661  0.025044  0.737905
# 2  0.464588  0.940235  0.709169  0.169721  0.247870
# 3  0.146446  0.792779  0.222903  0.870784  0.340836
# 4  0.743698  0.344687  0.299164  0.517687  0.120320
# X-bar平均值: 0.417002982417057
# R平均值: 0.7343395449701438
# X-bar控制限: (-0.006710935030715903, 0.84071689986483)
# R控制限: 1.5523937980668838

 

--------------------------------------

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']  # 防止中文标签乱码,还有通过导入字体文件的方法
plt.rcParams['axes.unicode_minus'] = False

# 假设您已经有了样本数据,存储在x_bar_values和R_values中

# 计算中心线和控制限
x_bar_centerline = np.mean(x_bar_values)
R_centerline = np.mean(R_values)
R_bar = np.mean(R_values)

# 计算控制限(通常使用常见的控制图常数,如A2,D3,D4)
A2 = 0.729
D3 = 0
D4 = 2.282
x_bar_UCL = x_bar_centerline + A2 * R_bar
x_bar_LCL = x_bar_centerline - A2 * R_bar
R_UCL = D4 * R_bar
R_LCL = D3 * R_bar

# 绘制X-bar图
plt.figure(figsize=(12, 6))
plt.subplot(2, 1, 1)
plt.plot(x_bar_values, marker='o', linestyle='-')
plt.axhline(y=x_bar_centerline, color='r', linestyle='--', label='中心线')
plt.axhline(y=x_bar_UCL, color='g', linestyle='--', label='上限控制限')
plt.axhline(y=x_bar_LCL, color='g', linestyle='--', label='下限控制限')
plt.title('X-bar图')
plt.xlabel('样本编号')
plt.ylabel('平均值')
plt.legend()
plt.grid()

# 绘制R图
plt.subplot(2, 1, 2)
plt.plot(R_values, marker='o', linestyle='-')
plt.axhline(y=R_centerline, color='r', linestyle='--', label='中心线')
plt.axhline(y=R_UCL, color='g', linestyle='--', label='上限控制限')
plt.title('R图')
plt.xlabel('样本编号')
plt.ylabel('范围 (R)')
plt.legend()
plt.grid()

plt.tight_layout()
plt.show()

This code will generate X-bar charts and R charts that help you monitor the average and range of your process in order to identify any anomalies or changes in your process. Please make appropriate modifications based on your data and needs. In actual applications, you may need to adjust control limits and constants based on the characteristics of the standard and process.

Guess you like

Origin blog.csdn.net/book_dw5189/article/details/133153507