代码绘制成果展示














代码解释


第一部分

# =========================================================================================# ====================================== 1. 环境设置 =======================================# =========================================================================================import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom scipy.stats import spearmanr, linregressimport matplotlib.gridspec as gridspec

第二部分

# =========================================================================================# ======================================2.颜色库=======================================# =========================================================================================COLOR_SCHEMES = {1: 'RdYlBu_r',}

第三部分

# =========================================================================================# ======================================3.绘图函数=======================================# =========================================================================================def plot_advanced_forest_chart(df, scheme_id):cmap_source = COLOR_SCHEMES[scheme_id] #提取配色方案if isinstance(cmap_source, str):cmap = plt.get_cmap(cmap_source)else:cmap = cmap_sourcewrap_threshold = 11 #y轴文本单行长度scatter_color = palette[-2] if num_vars > 1 else palette[0] #设置散点的默认颜色

第四部分

#创建画布fig = plt.figure(figsize=(16, 9))gs = gridspec.GridSpec(1, 2, width_ratios=[1, 2.3], wspace=0.22) #创建网格布局ax_a = fig.add_subplot(gs[0]) #左侧小提琴图#0值参考线ax_a.axvline(0, #xcolor='gray', #颜色linestyle='--', #样式alpha=0.7, #透明度linewidth=2) #粗细#x轴标题ax_a.set_xlabel("Residual (Sign-Log)", #文本fontsize=15, #大小fontweight='bold') #粗细ax_a.tick_params(axis='y', #轴which='major', #主刻度pad=45, #间隔length=0) #长度#x轴刻度设置ax_a.tick_params(axis='x', #轴labelsize=13) #大小

第五部分

#设置右侧热图网格布局gs_right = gridspec.GridSpecFromSubplotSpec(1, #行2, #列subplot_spec=gs[1], #位置width_ratios=[2.2, 0.05], #比例wspace=0.02) #间距#相关性散点矩阵布局gs_b = gridspec.GridSpecFromSubplotSpec(num_vars, #行num_vars, #列subplot_spec=gs_right[0], #位置wspace=0.08, #水平间距hspace=0.08 #垂直间距)norm = mcolors.Normalize(vmin=-1, vmax=1) #创建一个标准化对象为后续色彩映射做准备else:r, p = spearmanr(df.iloc[:, j], df.iloc[:, i]) #斯皮尔曼分析ax.set_facecolor(cmap(norm(r))) #当前网格单元的背景色#显著性设置if p < 0.001:stars = "***"elif p < 0.01:stars = "**"elif p < 0.05:stars = "*"else:stars = ""#文本颜色设置text_color = "black" if abs(r) < 0.6 else "white"#相关性文本设置ax.text(0.5, #x0.5, #yf"{r:.3f}\n{stars}", #文本ha='center', #水平va='center', #垂直fontsize=13, #大小color=text_color, #颜色transform=ax.transAxes, #坐标系)#轴刻度

第六部分

# 遍历所有子图for ax in fig.axes:#设置边框for spine in ax.spines.values():spine.set_linewidth(2)#设置刻度ax.tick_params(axis='both', #轴which='major', #主刻度length=5, # 长width=2) #宽# 设置颜色条刻度cbar.ax.tick_params(width=2,#粗细length=5, #长度labelsize=13) #大小cbar.outline.set_linewidth(2) #边框线

第七部分

#子图编号fig.text(0.1, #x0.95, #y'(a)', #编号fontsize=22, #大小fontweight='bold', #加粗va='top') #垂直fig.text(0.35, #x0.95, #y

第八部分

# =========================================================================================# ======================================4.执行部分======================================# =========================================================================================if __name__ == '__main__':df= pd.read_excel(r"Residual_Results.xlsx") #原始数据#是否批量绘图else:scheme_id = 1print('正在绘制并保存方案:', scheme_id)plot_advanced_forest_chart(df, scheme_id)

如何应用到你自己的数据

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


获取方式
