
代码绘制成果展示














代码解释


第一部分

# =========================================================================================# ====================================== 1. 环境设置 =======================================# =========================================================================================import osimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom matplotlib.gridspec import GridSpec, GridSpecFromSubplotSpecfrom matplotlib.colors import LinearSegmentedColormap

第二部分

# =========================================================================================# ======================================2.颜色库=======================================# =========================================================================================COLOR_SCHEMES = {1: ['#00A08A', '#9BD8C9', '#FDFDF5', '#FFB3B9', '#FF6B7A'],}

第三部分

# =========================================================================================# ======================================3.绘图函数=======================================# =========================================================================================def plot_advanced_forest_chart(data_bundle, scheme_id):df_X = data_bundle['X'] #特征数据#网格布局outer_gs = GridSpec(2, #行3, #列wspace=0.35, #行间距hspace=0.35) #列间距titles = ["(a)", "(b)", "(c)", "(d)", "(e)", "(f)"] #子图编号

第四部分

#遍历特征for i in range(len(features)):feature_name = features[i] #特征名x_data = df_X[feature_name].values #特征数据s_data = shap_vals[:, i] #SHAP值#子图布局inner_grid = GridSpecFromSubplotSpec(2, #行1, #列subplot_spec=outer_gs[i], #位置height_ratios=[4, 1], #高度比hspace=0.08) #层高间距

第五部分

ax_main = fig.add_subplot(inner_grid[0]) #主图#遍历边框for spine in ax_main.spines.values():spine.set_linewidth(1.5) #边框粗细#绘制中位数线ax_main.axvline(median_val, #xcolor='gray', #颜色linestyle='--', #虚线linewidth=1.2, #粗细label=f'Median: {median_val:.2f}') #文本标注#阈值线ax_main.axvline(threshold_val, #xcolor='red', #颜色linestyle='--', #虚线linewidth=1.2, #粗细alpha=0.7, #透明度label=f'Threshold: {threshold_val:.2f}') #文本标注

第六部分

#双Y轴ax_pdp = ax_main.twinx()ax_pdp.plot(pdp_x, #xpdp_y, #ycolor='dimgray', #颜色linewidth=2, #粗细label='PDP') #图例名lines2, labels2 = ax_pdp.get_legend_handles_labels() #获取副图例#副图例ax_pdp.legend(lines2, #副图例项labels2, #副图例标签loc='upper center', #位置bbox_to_anchor=(0.5, 1.15), #坐标ncol=2, #列frameon=False) #无边框

第七部分

ax_hist = fig.add_subplot(inner_grid[1], sharex=ax_main) #加直方图共用X轴#遍历直方图边框for spine in ax_hist.spines.values():spine.set_linewidth(1.5) #粗细hist_cax = hist_divider.append_axes("right",size="5%",pad=0.6)hist_cax.axis('off') #去掉占位轴

第八部分

# =========================================================================================# ======================================4.执行部分=======================================# =========================================================================================if __name__ == "__main__":df_full = pd.read_excel(r"data.xlsx") #读取原始数据df_X = df_full.iloc[:, :-1] #xdf_y = df_full.iloc[:, -1] #yfeature_names = df_X.columns.tolist() #特征名X_train, X_test, y_train, y_test = train_test_split(df_X, df_y, test_size=0.2, random_state=42) #划分数据

第九部分

xgb_model = XGBRegressor(random_state=42) #初始化模型#超参数param_grid = {'n_estimators': [5, 10,20,30],'max_depth': [3, 5,]}grid_search = GridSearchCV(estimator=xgb_model, param_grid=param_grid, cv=3, scoring='r2', n_jobs=-1) #网格搜索grid_search.fit(X_train, y_train) #拟合best_model = grid_search.best_estimator_ #最佳模型

第十部分

explainer = shap.TreeExplainer(best_model) #SHAP解释器shap_values = explainer.shap_values(df_X) #SHAP值mean_abs_shap = np.abs(shap_values).mean(axis=0) #SHAP绝对值均值print("-" * 40)

第十一部分

# 打包绘图数据df_real = {'X': df_X,'shap': sorted_shap,'pdp': pdp_results,'features': sorted_features}scheme_id = 1plot_advanced_forest_chart(df_real, scheme_id)print(f'正在绘制并保存配色方案:{scheme_id}')

如何应用到你自己的数据

1.设置原始数据的保存路径,执行部分:
df_full = pd.read_excel(r"data.xlsx")2.提取特征数据和目标数据,执行部分:
df_X = df_full.iloc[:, :-1]df_y = df_full.iloc[:, -1]
3.设置超参数网格,执行部分:
param_grid = {'n_estimators': [20,80,100],'max_depth': [3, 5,]}
4.设置是否要进行批量绘图,执行部分:
plot_all = False5.设置绘图结果的保存地址,绘图函数部分:
fig.savefig(fr"Scheme_{scheme_id}.png",dpi=300, bbox_inches='tight')
推荐


获取方式
