python在一张中绘制N×M个子图,按周期对数据进行分组,输入df为dataFrame数据格式,具体特征按照实际的业务需求来,这里第25个周期数据为异常数据,通过颜色特别标识出来。
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
features = ["太阳轮负载", "下盘负载", "齿圈负载",
"上盘负载", "真实压力值"]
steps = [5, 6, 7, 8]
# 分组:按周期ID进行分组,每个周期应该包含1到11的所有步骤
grouped = df.groupby('周期ID')
# 创建子图:N=4(步序数量),M=9(特征数量)
fig, axes = plt.subplots(nrows=len(steps), ncols=len(features), figsize=(20, 12))
# 为每个步序和特征绘图
for i, step in enumerate(steps):
for j, feature in enumerate(features):
ax = axes[i, j] # 获取对应的子图
# # 在每个步序上过滤数据
# group = grouped[grouped['工艺步序'] == step]
# group.reset_index(drop=True, inplace=True)
# 绘制每个特征的曲线
for period, group_data in grouped:
if not set(group_data['工艺步序'].unique()).issuperset(set(range(1, 12))):
continue
else:
group_data = group_data[group_data['工艺步序'] == step] # 只考虑前5个步骤
group_data.reset_index(drop=True, inplace=True)
if i > 0 :
if period != 25:
if period == 22:
ax.plot(range(50), group_data[feature][:50], 'r', label=f"异常批次的上一批--{period}")
else:
ax.plot(range(50), group_data[feature][:50], color='#C2DCB1', linestyle='--')
else:
# 绘制特征数据
if period == 25:
ax.plot(range(50), group_data[feature][:50], 'r', label=f"异常批次--{period}")
else:
ax.plot(range(50), group_data[feature][:50], color='#C2DCB1', linestyle='--')
ax.set_title(f"{feature} - 步序 {step}")
ax.set_ylabel(f"{feature}", color='b')
# 设置y轴字体颜色
# for label in ax.get_yticklabels():
# label.set_color('b')
ax.legend(loc='upper left')
# 自动调整布局
plt.tight_layout()
plt.savefig('特征-步序.png', dpi=600)
plt.show()