
代码绘制成果展示










代码解释


第一部分

# =========================================================================================# ====================================== 1. 环境设置 =======================================# =========================================================================================import numpy as npimport matplotlib.pyplot as pltimport seaborn as snsfrom matplotlib.gridspec import GridSpecfrom scipy import statsimport pandas as pdimport matplotlibmatplotlib.rcParams['pdf.fonttype'] = 42matplotlib.rcParams['ps.fonttype'] = 42import osplt.rcParams['font.family'] = 'serif'plt.rcParams['font.serif'] = ['Times New Roman']plt.rcParams['axes.unicode_minus'] = Falseplt.rcParams['mathtext.fontset'] = 'stix'plt.rcParams['font.size'] = 12

第二部分

# =========================================================================================# ======================================2.颜色库=======================================# =========================================================================================COLOR_SCHEMES= {1: ['#4d4d4d', '#ff9f4b', '#1f77b4'],}scheme_index= 40#选择配色方案

第三部分

GridSpec 创建一网格布局。# =========================================================================================# ======================================3.绘图函数=========================================# =========================================================================================def plot_simulation_results(data):c_a, c_b, c_c = colors[0], colors[1], colors[2] #分配颜色fig = plt.figure(figsize=(10, 10)) #创建画布# 定义网格布局gs = GridSpec(2, #行2, #列figure=fig, # 绑定到当前figurehspace=0.05, #子图垂直间距wspace=0.05, #子图水平间距height_ratios=[1, 5], # 设置行高比例,顶部边际图占1份,主图占5份width_ratios=[5, 1]) # 设置列宽比例,主图占5份,右侧边际图占1份ax_main = fig.add_subplot(gs[1, 0]) # 添加主散点图坐标轴ax_top = fig.add_subplot(gs[0, 0], sharex=ax_main) # 添加顶部KDE图坐标轴,与主图共享X轴ax_right = fig.add_subplot(gs[1, 1], sharey=ax_main) # 添加右侧KDE图坐标轴,与主图共享Y轴

第四部分

# 绘制A组散点图ax_main.scatter(grp_a_x, #X坐标grp_a_y, #Y坐标c=c_a, #颜色alpha=0.3, #透明度s=20, #点的大小label=f'Group A', #图例标签edgecolors='none') #无边框# 绘制B组散点图ax_main.scatter(grp_b_x, #X坐标grp_b_y, #Y坐标c=c_b, #颜色alpha=0.3, #透明度s=20, #点的大小label=f'Group B', #图例标签edgecolors='none') #无边框# 绘制C组散点图ax_main.scatter(grp_c_x, #X坐标grp_c_y, #Y坐标c=c_c, #颜色alpha=0.6, #透明度s=30, #点的大小label=f'Group C', #图例标签edgecolors='none') #无边框ax_main.set_xlim(-70, 70) #主图X轴范围ax_main.set_ylim(-70, 70) #主图Y轴范围

第五部分

bandwidth = 0.05 #KDE的带宽调节参数#顶部A组X轴数据的密度曲线sns.kdeplot(grp_a_x, #数据ax=ax_top, #指定坐标轴color=c_a, #颜色fill=True, #填充曲线下方alpha=0.3, #透明度linewidth=1, #线宽bw_adjust=bandwidth) #带宽#顶部图B组X轴数据的密度曲线sns.kdeplot(grp_b_x, #数据ax=ax_top, #指定坐标轴color=c_b, #指定颜色fill=True, #填充曲线下方alpha=0.3, #透明度linewidth=1, #线宽bw_adjust=bandwidth) #带宽#顶部C组X轴数据的密度曲线sns.kdeplot(grp_c_x, #数据ax=ax_top, #坐标轴color=c_c, #颜色fill=True, #填充曲线下方alpha=0.3, #透明度linewidth=1, #线宽bw_adjust=bandwidth) # 带宽参数

第六部分

# 在主图中创建嵌入式坐标轴ax_inset = ax_main.inset_axes([0.5,#左0.05,#下0.45,#宽0.25])#高flierprops=dict(marker='d', #异常值点设为菱形markersize=4, #异常点大小markerfacecolor='black', #异常点颜色alpha=0.5), #异常点透明度boxprops=dict(linewidth=1.5), #箱体边框线宽medianprops=dict(linewidth=1.5, #中位数线宽color='black'), #中位数线颜色whiskerprops=dict(linewidth=1.5), # 线线宽capprops=dict(linewidth=1.5)) #须线末端横杠线宽ax_inset.set_title("Residuals", #嵌入图标题fontsize=12, #字体大小fontweight='bold') #加粗ax_inset.set_yticks([]) # 隐藏嵌入图Y轴刻度ax_inset.set_xlabel("") # 清空嵌入图X轴标签

第七部分

#显著性标记函数def get_stars(p):if p < 0.0001:return "****"elif p < 0.001:return "***"elif p < 0.01:return "**"elif p < 0.05:return "*"else:return "ns"ax.text(x_line + 1.5, #X坐标(y1 + y2) / 2, #Y坐标star, #星号ha='left', # 水平对齐va='center', # 垂直对齐rotation=270, # 旋转fontsize=10, # 字体大小fontweight='bold') # 字体加粗

第八部分

#添加C和B的显著性标记add_sig(ax_inset,resid_c, resid_b, 1, 2, 1)#添加B和A的显著性标记add_sig(ax_inset,resid_b,resid_a, 2,3,2)#添加C和A的显著性标记add_sig(ax_inset, resid_c,resid_a,1,3,3)curr_xlim = ax_inset.get_xlim() # 获取当前嵌入图X轴范围#设置范围ax_inset.set_xlim(curr_xlim[0], curr_xlim[1] * 1.3)# 收集所有坐标轴对象all_axes = [ax_main,ax_top,ax_right,ax_inset]ax.minorticks_on() # 开启次刻度#保存plt.savefig(fr"{scheme_index}.png", dpi=300, bbox_inches='tight')plt.savefig(fr"{scheme_index}.pdf", bbox_inches='tight')

第九部分

# =========================================================================================# ======================================4.执行部分=========================================# =========================================================================================if __name__ == "__main__":df = pd.read_excel(r"data.xlsx") # 读取数据all_x = df['X'].values #Xall_y = df['Y'].values #Yslope_fit, intercept_fit, r_value, p_value, std_err = stats.linregress(all_x, all_y) #线性回归拟合print(f"回归模型拟合完成: y = {slope_fit:.4f}x + {intercept_fit:.4f}")#数据处理函数def process_group(group_name):sub_df = df[df['Group'] == group_name] # 筛选出指定组名的数据子集if sub_df.empty: # 如果为空return np.array([]), np.array([]), np.array([]) # 返回空的数组x = sub_df['X'].values #Xy = sub_df['Y'].values #Ypred = slope_fit * x + intercept_fit # 根据模型计算预测值resid = y - pred # 计算残差return x, y, resid # 返回X数据,Y数据和残差grp_a_x, grp_a_y, resid_a = process_group('A') #处理A组数据grp_b_x, grp_b_y, resid_b = process_group('B') #处理B组数据grp_c_x, grp_c_y, resid_c = process_group('C') #处理C组数据# 将处理后的数据打包成字典data_pack = {'grp_a': (grp_a_x, grp_a_y, resid_a), # A组数据包'grp_b': (grp_b_x, grp_b_y, resid_b), # B组数据包'grp_c': (grp_c_x, grp_c_y, resid_c), # C组数据包'reg': (slope_fit, intercept_fit), # 回归参数包'all_resid': np.concatenate([resid_a, resid_b, resid_c]) # 合并所有残差用于后续计算范围}# 调用绘图函数plot_simulation_results(data_pack)

如何应用到你自己的数据

1.设置颜色方案:
scheme_index= 40#选择配色方案2.设置绘图结果的保存地址:
plt.savefig(fr"{scheme_index}.png", dpi=300, bbox_inches='tight')plt.savefig(fr"{scheme_index}.pdf", bbox_inches='tight')
3.设置原始数据的保存路径:
df = pd.read_excel(r"data.xlsx") # 读取数据3.设置x、y轴的数据:
all_x = df['X'].values #Xall_y = df['Y'].values #Y

推荐


获取方式
