
代码绘制成果展示














代码解释


第一部分

# =========================================================================================# ====================================== 1. 环境设置 =======================================# =========================================================================================import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.colors as mcolorsfrom matplotlib.collections import LineCollection

第二部分

# =========================================================================================# ======================================2.颜色库============================================# =========================================================================================COLOR_SCHEMES = {1: ['#2c5d87', '#00593b', '#21a257', '#0da7b3'],}

第三部分

# =========================================================================================# ======================================3.绘图函数============================================# =========================================================================================def plot_advanced_forest_chart(df, scheme_id, mode='classic'):colors = COLOR_SCHEMES[scheme_id] #提取配色方案df_numeric = df.select_dtypes(include=['number']) #筛选出数值列labels = df_numeric.columns.tolist() #列名,用作X轴标签data = [df_numeric[col].values for col in labels] #遍历提取每列的数值data_for_boxplot = [d[~np.isnan(d)] for d in data] #剔除空值n_cols = len(labels) #计算列数,要比较和展示的组数n_patients = len(df_numeric) #计算行数,样本总数量

第四部分

#创建画布fig, ax = plt.subplots(figsize=(6, 8), dpi=300)#设置边框ax.spines['left'].set_linewidth(2)ax.spines['bottom'].set_linewidth(2)ax.tick_params(axis='y', #轴which='major', #主刻度length=5,#长度width=2,#粗细direction='out',#朝外labelsize=14) #大小

第五部分

#箱线图bp = ax.boxplot(data_for_boxplot, #数据positions=list(range(n_cols)), #xwidths=0.6, #宽度patch_artist=True, #允许颜色填充或样式修改showfliers=False) #异常值#遍历每一个箱体对象配置样式for i in range(n_cols):c = '#b0b0b0' if mode == 'classic' else colors[i] #颜色bp['caps'][i * 2 + 1].set(color=c, linewidth=2.5) #顶部横线

第六部分

np.random.seed(42) #随机种子x_jitter = np.random.uniform(-0.12, 0.12, (n_patients, n_cols)) #点偏移量#遍历样本for i in range(n_patients):#判断绘图样式if mode == 'classic':ax.plot(x_coords, #xy_coords, #ycolor='gray', #颜色linestyle='--', #样式alpha=0.5, #配对连线透明度zorder=1, #层linewidth=1.2) #粗细lc = LineCollection(segments, #线段集合colors=c_seg[:-1], #颜色linewidths=1.2, #线宽zorder=1) #层ax.add_collection(lc) #添加道图上

第七部分

#遍历样本点for j in range(n_cols):ax.scatter(x_coords[j], #xy_coords[j], #ycolor=colors[j], #颜色s=80, #大小edgecolor='black', #边缘线颜色linewidth=1.5, #边缘线粗细zorder=3) #层

第八部分

#显著性辅助函数def add_stat_annotation(ax, x1, x2, y, p_val):gap = 0.05 #差异标识横线两端留白ax.plot([x1 + gap, x2 - gap], #x[y, y], #ycolor='black', #颜色lw=1.2) #粗细#两端垂线长度tick_len = (y_max - y_min) * 0.02#p值格式化if p_val < 0.001:text = "$p < 0.001$"else:text = f"{p_val:.3f}"#标注ax.text((x1 + x2) / 2, #xy + (y_max - y_min) * 0.01, #ytext, #文本ha='center', #水平va='bottom', #垂直fontsize=14, #字体大小)

第九部分

#极值y_max = np.max([np.max(d[~np.isnan(d)]) for d in data])y_min = np.min([np.min(d[~np.isnan(d)]) for d in data])h_step = (y_max - y_min) * 0.12 #统计线递增阶梯#提取数据clean_data_i = data[i]clean_data_j = data[j]stat, p_val = wilcoxon(clean_data_i, clean_data_j) #Wilcoxon秩检验y_annot = y_max + h_step * mult #横线y坐标add_stat_annotation(ax, i, j, y_annot, p_val) #调用函数绘制

第十部分

# =========================================================================================# ======================================4.执行部分============================================# =========================================================================================if __name__ == '__main__':excel_filename = r"data.xlsx"#原始数据df_real = pd.read_excel(excel_filename)#读取#是否批量绘图selected_hex_colors = COLOR_SCHEMES[scheme_id]print('正在绘制并保存方案:', scheme_id)plot_advanced_forest_chart(df_real, scheme_id, mode='colored')plot_advanced_forest_chart(df_real, scheme_id, mode='classic')

如何应用到你自己的数据

1.设置原始数据的保存路径,执行部分:
df_real = pd.read_excel(r"data.xlsx")2.设置是否要进行批量绘图,执行部分:
plot_all = True3.设置绘图结果的保存地址,执行部分:
plt.savefig(fr"plot_scheme_{scheme_id}_{suffix}.png", format='png', bbox_inches='tight')
推荐


获取方式
