
代码绘制成果展示














代码解释


第一部分

# =========================================================================================# ====================================== 1. 环境设置 =======================================# =========================================================================================import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec

第二部分

# =========================================================================================# ======================================2.颜色库=======================================# =========================================================================================COLOR_SCHEMES = {1: ['#E74C3C', '#3B4A6B', '#1C8C85'],}

第三部分

# =========================================================================================# =====================================3.绘图函数=======================================# =========================================================================================def plot_advanced_forest_chart(df_real, scheme_id):# 分组unique_sources = df_real['Source'].unique()selected_hex_colors = COLOR_SCHEMES[scheme_id] # 配色方案#动态分配颜色和标记形状markers = ['s', '^', 'o', 'D', 'v', '<', '>']#用于存储图例样式source_styles = {}

第四部分

# 创建画布fig = plt.figure(figsize=(14, 7))# 创建网格gs_base = gridspec.GridSpec(1, # 行2, # 列width_ratios=[1, 1], # 比例wspace=0.1, # 宽度间距left=0.06, # 左边距right=0.98, # 右边距top=0.95, # 上边距bottom=0.08) # 下边距ax_leg = fig.add_subplot(gs_right[0])ax3 = fig.add_subplot(gs_right[1])

第五部分

min_v = min(y_true_all.min(), y_pred_all.min()) # 全局最小值max_v = max(y_true_all.max(), y_pred_all.max()) # 全局最大值scatter_handles = [] #散点句柄scatter_labels = [] #散点标签# 设置子图编号ax1.set_title('(a)', # 文本fontsize=14, # 字号fontweight='bold', # 加粗loc='left', # 水平pad=10) # 边距ax1.set_xticklabels([]) # 隐藏x轴刻度标签# 标注到图上ax1.text(0.95, # xbbox=dict(boxstyle='square,pad=0.5', # 文本框样式facecolor='white', # 背景色edgecolor='gray', # 边框色alpha=0.9)) # 透明度

第六部分

apply_local_format(ax2) # 格式化残差子图max_err = 0 # 初始最大误差err_bound = max(40, max_err * 1.1) # 设置y轴边界ax2.set_xlim(dynamic_min, dynamic_max) # x轴范围ax2.set_ylim(-err_bound, err_bound) # y轴范围# 设置x轴标题ax2.set_xlabel(r'Measured $\epsilon_{sh}$ ($\mu\epsilon$)', # 文本fontsize=13, # 字号fontweight='bold') # 加粗# 设置y轴标题ax2.set_ylabel('Relative error (%)', # 文本fontsize=13, # 字号fontweight='bold') # 加粗# 图例ax2.legend(loc='upper right', # 位置ncol=2, # 列frameon=False, # 无边框prop={'size': 11}) # 字号属性

第七部分

ax_leg.axis('off') # 关闭图例坐标轴# 添加编号ax_leg.set_title('(b)', # 文本fontsize=14, # 字号fontweight='bold', # 加粗loc='left', # 水平pad=10) # 标题边距# 添加右上角图例ax_leg.legend(handles=[*patch_handles, line_normal], #句柄loc='center', # 位置居中mode="expand", # 展开bbox_to_anchor=(0, 0, 1, 1), ncol=2, # 图例锚点及列布局prop={'size': 11}, # 字号edgecolor='gray', # 边框色framealpha=1) # 透明

第八部分

apply_local_format(ax3) # 格式化子图# 绘制x=0线ax3.axvline(0, # xcolor='black', # 黑色lw=1.8, # 线宽zorder=5) # 层# 绘制负RMSE参考线ax3.axvline(-rmse, # xcolor='gray', # 灰色lw=1.5, # 线宽ls='--', # 虚线zorder=5) # 层# 绘制正RMSE参考线ax3.axvline(rmse, # xcolor='gray', # 灰色lw=1.5, # 线宽ls='--', # 虚线zorder=5) # 层ax3.text(rmse + (res_limit * 0.02), # xylim_top, # yrf'$+RMSE ({rmse:.0f}\ \mu\epsilon)$', # 文本rotation=90, # 旋转color='gray', # 颜色va='top', # 垂直

第九部分

# =========================================================================================# ======================================4.执行部分=======================================# =========================================================================================if __name__ == "__main__":excel_path = r'data.xlsx' # 数据路径df_raw = pd.read_excel(excel_path) # 读取X_train = X_train_full.drop(columns=['Source']) #剔除分组X_test = X_test_full.drop(columns=['Source']) #剔除分组#测试集df_test = df_raw.loc[X_test.index].copy()#定义参数网格param_grid = {'n_estimators': [50, 100, 150],'learning_rate': [0.05, 0.1],'max_depth': [3, 4, 5]}

如何应用到你自己的数据

1.设置原始数据的保存路径,执行部分:
excel_path = r'data.xlsx'2.分离数据,执行部分:
X = df_raw.drop(columns=['Measured', 'Source']) #xy = df_raw['Measured'] #y
3.划分训练数据和测试数据,执行部分:
#划分数据X_train_full, X_test_full, y_train, y_test = train_test_split(df_raw.drop(columns=['Measured']), #xdf_raw['Measured'], #ytest_size=0.2, #比例random_state=42, #种子stratify=df_raw['Source'] #分层)X_train = X_train_full.drop(columns=['Source']) #剔除分组X_test = X_test_full.drop(columns=['Source']) #剔除分组
4.设置参数网格,执行部分:
param_grid = {'n_estimators': [50, 100, 150],'learning_rate': [0.05, 0.1],'max_depth': [3, 4, 5]}
5.设置是否进行批量绘图,执行部分:
plot_all = True6.提取分组信息,绘图函数部分:
# 分组unique_sources = df_real['Source'].unique()
7.设置绘图结果的保存地址,绘图函数部分:
plt.savefig(fr'Scheme_{scheme_id}.svg', bbox_inches='tight')
推荐


获取方式
