
代码绘制成果展示














代码解释


第一部分

# =========================================================================================# ====================================== 1. 库的导入 =========================================# =========================================================================================import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspecimport matplotlibimport xgboost as xgbimport shap

第二部分

# =========================================================================================# ====================================== 2.颜色库 =========================================# =========================================================================================COLOR_SCHEMES = {1: (['#e41a1c', '#377eb8', '#4daf4a'], LinearSegmentedColormap.from_list('c1', ['#008080', '#FFFFFF', '#FF7F50'])),}

第三部分

# =========================================================================================# ======================================3.蜂群图辅助函数=======================================# =========================================================================================def simple_beeswarm(x_values, nbins=40, width=0.1):np.random.seed(42)hist_range = (np.min(x_values), np.max(x_values)) #数据的最小值和最大值范围if hist_range[0] == hist_range[1]: # 如果最大值等于最小值hist_range = (hist_range[0] - 0.1, hist_range[1] + 0.1) #手动扩展范围current_width = (counts[i] / max_count) * width # 根据当前箱子的密度计算抖动宽度ys = np.linspace(-current_width, current_width, len(idxs)) # 在宽度范围内生成均匀分布的Y值np.random.shuffle(ys) # 打乱Y值顺序y_values[idxs] = ys # 将计算好的Y值赋给对应的数据点return y_values # 返回计算好的Y轴抖动坐标

第四部分

# =========================================================================================# ====================================== 4.3D饼图 =========================================# =========================================================================================def draw_3d_pie_chart_on_ax(ax, sizes, colors, labels, tilt_angle=0.4, depth_layers=80,total_thickness=0.5):step = total_thickness / depth_layers #计算每一层的厚度# 循环按层绘制实现堆叠的3D效果for i in range(depth_layers):#绘制表层饼图wedges, texts, autotexts = ax.pie(sizes, #数据colors=colors, #颜色startangle=90, #角度radius=1.2, #半径autopct='%1.2f%%', #文本pctdistance=0.6, #文本距圆心的相对距离shadow=False #关闭默认的阴影效果)#文本样式for autotext in autotexts:autotext.set_fontsize(11) #字体大小autotext.set_fontweight('bold') #加粗autotext.set_color('black') #颜色autotext.set_zorder(depth_layers + 3) #层ax.set_aspect(tilt_angle) #角度#加图例ax.legend(wedges,#图例对象labels, #标签loc="center left", #位置bbox_to_anchor=(0.92, 0.5), #坐标frameon=False, #边框fontsize=14, #字体大小handletextpad=0.5) #间距

第五部分

# =========================================================================================# ======================================5.shap重要性散点组图=========================================# =========================================================================================def plot_custom_shap_dual_axis(ax_bar, ax_scatter, shap_values, X_df, scheme_colors, cmap,max_features=15):mean_abs_shap = np.abs(shap_values.values).mean(axis=0) #每个特征SHAP绝对值的平均数order = np.argsort(mean_abs_shap)[::-1] #排序top_indices = order[:max_features] #前15个最重要的特征other_indices = order[max_features:] #其它特征#拼接名字top_features = [X_df.columns[i] for i in top_indices] + ["other features"]top_features.reverse() #倒序y_pos = np.arange(len(top_features)) #每个特征的y坐标total_mean = sum(mean_abs_shap) #所有特征的总重要性,用来求百分比bar_color_pos = matplotlib.colors.to_rgba(scheme_colors[0], alpha=0.25) #正向色bar_color_neg = matplotlib.colors.to_rgba(scheme_colors[1], alpha=0.25) #负向色bar_color_neutral = matplotlib.colors.to_rgba('grey', alpha=0.15) #其它特征颜色if feature == "other features":bar_color = bar_color_neutral #使用灰色else:bar_color = bar_color_pos if corr >= 0 else bar_color_neg #大于0用正向色,小于0用负向色#百分比ax_bar.text(max(plot_mean_abs) * 1.1, #xidx, #yf"{pct:.2f}%", #文本va='center', #垂直ha='left', #水平fontsize=14) #大小ax_bar.set_yticks(y_pos) #左侧y轴刻度位置ax_bar.set_yticklabels(top_features, fontsize=14) #y轴刻度标注特征文本ax_bar.set_xlabel('mean(|SHAP value|)', fontsize=16, fontweight='bold') #x轴标题#边框ax_scatter.spines['bottom'].set_visible(False)ax_scatter.spines['right'].set_visible(False)

第六部分

# =========================================================================================# ======================================6.组图绘制函数=========================================# =========================================================================================def plot_advanced_forest_chart(analysis_results, scheme_id, selected_colors_tuple, grid_cols=3):scheme_colors = selected_colors_tuple[0] #饼图配色cmap_name = selected_colors_tuple[1] #蜂巢图配色hr = [3, 1] * grid_rows #每行高度比例,主图:饼图#创建画布gs = gridspec.GridSpec(grid_rows * 2, #行grid_cols, #列height_ratios=hr, #高度比hspace=0.05, #上下间距wspace=0.45) #左右间距titles = [f'({chr(97 + i)}) {target_name}' for i, target_name in enumerate(targets_keys)] #标题cmap = plt.get_cmap(cmap_name) if isinstance(cmap_name, str) else cmap_name #获取对应的Colormap对象ax_pie = fig.add_subplot(gs_bottom[0]) #饼图轴#饼图绘制draw_3d_pie_chart_on_ax(ax_pie, #轴res['pie_sizes'], #数据scheme_colors, #颜色['X_3D', 'X_ND', 'X_LM'],#图例标签tilt_angle=0.6, #角度total_thickness=0.45, #厚度depth_layers=60) #层数#饼图标题ax_pie.set_title('Relative Contribution', #文本x=1.38,#xy=-0.32, #yfontsize=20, #字体大小fontweight='bold') #加粗ax_txt = fig.add_subplot(gs_bottom[1]) #右侧评估结果部分ax_txt.axis('off') #清空text_content = f"R² = {res['R2']:.3f}\n\nMSE = {res['MSE']:.3f}\n\nRMSE = {res['RMSE']:.3f}\n\nMAE = {res['MAE']:.3f}" #拼接文本

第七部分

# =========================================================================================# ======================================7.执行部分 =========================================# =========================================================================================if __name__ == '__main__':#类别划分features_3d = ['H_MN', 'H_SD', 'Volume', 'H_SUM']features_nd = ['NDVI_MN', 'NDVI_SD', 'NDVI_SUM']features_lm = ['NP', 'MESH', 'SHAPE', 'COHESION', 'FRAC', 'PD', 'AI', 'LSI', 'LPI', 'TE', 'PAFRAC', 'CA','DIVISION', 'PARA', 'PLAND', 'SPLIT', 'ED']excel_data_path = r"data.xlsx" #原始数据excel_file = pd.ExcelFile(excel_data_path) #读取target_names = excel_file.sheet_names #读取表名就是目标名#遍历每个目标for target_name in target_names:df_sheet = pd.read_excel(excel_data_path, sheet_name=target_name) #读取当前表#提取特征数据和目标数据if target_name in df_sheet.columns:y = df_sheet[target_name]X = df_sheet.drop(columns=[target_name])else:y = df_sheet.iloc[:, -1]X = df_sheet.iloc[:, :-1]#划分数据X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)model = xgb.XGBRegressor(random_state=42) #初始化XGBoost回归模型#初始化网格搜索grid = GridSearchCV(model, param_grid, cv=3, scoring='neg_mean_squared_error')grid.fit(X_train, y_train) #拟合best_model = grid.best_estimator_ #最佳模型print("-" * 50)target_columns = 3 #组合图每一行的子图数plot_advanced_forest_chart(df_real, scheme_id, selected_colors_tuple, grid_cols=target_columns)

如何应用到你自己的数据

1.设置特征数据的分类,执行部分:
features_3d = ['H_MN', 'H_SD', 'Volume', 'H_SUM']features_nd = ['NDVI_MN', 'NDVI_SD', 'NDVI_SUM']features_lm = ['NP', 'MESH', 'SHAPE', 'COHESION', 'FRAC', 'PD', 'AI', 'LSI', 'LPI', 'TE', 'PAFRAC', 'CA','DIVISION', 'PARA', 'PLAND', 'SPLIT', 'ED']
2.设置原始数据的保存地址,执行部分:
excel_data_path = r"data.xlsx" #原始数据3.设置超参数,执行部分:
param_grid = {'max_depth': [3, 4],'n_estimators': [50, 100],'learning_rate': [0.05, 0.1]}
4.设置是否要进行批量绘图,执行部分:
plot_all = True5.设置绘图结果的保存地址,主绘图函数部分:
plt.savefig(fr"advanced_shap_scheme_{scheme_id}.png", dpi=300, bbox_inches='tight')
推荐


获取方式
