
代码绘制成果展示










代码解释


第一部分

# =========================================================================================# ====================================== 1. 环境设置 =======================================# =========================================================================================import matplotlib.pyplot as pltimport seaborn as snsimport numpy as npimport pandas as pdfrom matplotlib.patches import Rectanglefrom scipy import statsplt.rcParams['font.family'] = 'serif'plt.rcParams['font.serif'] = ['Times New Roman']plt.rcParams['axes.unicode_minus'] = Falseimport matplotlibmatplotlib.rcParams['pdf.fonttype'] = 42matplotlib.rcParams['ps.fonttype'] = 42

第二部分

# =========================================================================================# ======================================2.颜色库============================================# =========================================================================================COLOR_SCHEMES = {1: ('RdBu_r', 'coolwarm'),}

第三部分

# =========================================================================================# ======================================4.绘图函数============================================# =========================================================================================def plot_advanced_correlation_chart(df_corr_a, df_corr_b, p_matrix_a, p_matrix_b, labels_diag, scheme_id,color_schemes):num_vars = len(labels_diag) #变量数量annot_combined_text = np.empty_like(df_corr_a.values, dtype=object) #用于存放带星号的注释文本# 遍历行#转为DataFrame供热力图调用df_annot_combined = pd.DataFrame(annot_combined_text, #注释文本index=labels_diag, #行标签columns=labels_diag) #列标签

第四部分

mask_a = np.ones_like(df_corr_a, dtype=bool) #初始化A区全掩码mask_a[np.triu_indices_from(mask_a, k=1)] = False #开放上三角,遮挡其余部分plt.subplots_adjust(left=0.20, #左right=0.80, #右top=0.85, #上bottom=0.08) #下

第五部分

cmap_a, cmap_b = color_schemes[scheme_id] #提取配色sns.heatmap(df_corr_a, #数据mask=mask_a, #上三角掩码annot=df_annot_combined, #文本fmt='s', #字符串cmap=cmap_a, #配色ax=ax, #轴**common_heatmap_kws) #参数#下三角热力图sns.heatmap(df_corr_b,#数据mask=mask_b, #下三角掩码annot=df_annot_combined, #文本fmt='s', #字符串cmap=cmap_b, #配色ax=ax, #轴**common_heatmap_kws) #参数

第六部分

ax.set_aspect('equal') #X轴Y轴比例#遍历变量名对角线填充变量标签ax.set_xticks([]) #去掉X轴刻度线ax.set_xticklabels([]) #去掉X轴刻度文本ax.set_yticks([]) #去掉Y轴刻度线ax.set_yticklabels([]) #去掉Y轴刻度文本#标题ax.set_title("Correlations analysis", #文本fontsize=12, #大小fontweight='bold', #加粗pad=20) #间距

第七部分

cbar_width = 0.02 #颜色条宽度cbar_height_ratio = 0.9 #颜色条相对主图的高度占比cbar_bottom = ax.get_position().y0 + ax.get_position().height * (1 - cbar_height_ratio) / 2 #颜色条y轴起始点cbar_height = ax.get_position().height * cbar_height_ratio #颜色条绝对高度gap_heatmap_to_cbar = 0.02 #主图边缘到颜色条的水平间距heatmap_left = ax.get_position().x0 #主图左侧x坐标heatmap_right = ax.get_position().x1 #主图右侧x坐标cb_b.ax.yaxis.set_ticks_position('left') #左侧颜色条刻度线cb_b.ax.yaxis.set_label_position('left') #左侧颜色条刻度数值cb_a.ax.tick_params(labelsize=8) #右侧颜色条刻度字体大小cb_b.ax.tick_params(labelsize=8) #左侧颜色条刻度字体大小

第八部分

# =================================================================================================# ======================================5.执行部分=====================================================# =================================================================================================if __name__ == '__main__':excel_file_path = r'data.xlsx'#原始数据#读取两个区域的数据df_data1 = pd.read_excel(excel_file_path, sheet_name='Region_A')df_data2 = pd.read_excel(excel_file_path, sheet_name='Region_B')plot_all = Trueif plot_all:for scheme_id in COLOR_SCHEMES.keys():selected_hex_colors = COLOR_SCHEMES[scheme_id]print('正在绘制并保存方案:', scheme_id)plot_advanced_correlation_chart(df_corr_a, #相关系数df_corr_b, #相关系数p_matrix_a, #p值p_matrix_b, #p值labels_diag, #变量名scheme_id, #配色方案COLOR_SCHEMES) #颜色库else:scheme_id = 1selected_hex_colors = COLOR_SCHEMES[scheme_id]print('正在绘制并保存方案:', scheme_id)plot_advanced_correlation_chart(df_corr_a, df_corr_b, p_matrix_a, p_matrix_b, labels_diag, scheme_id,COLOR_SCHEMES)

如何应用到你自己的数据

1.设置原始数据的保存路径,执行部分:
excel_file_path = r'data.xlsx'#原始数据2.读取两个区域的数据,执行部分:
df_data1 = pd.read_excel(excel_file_path, sheet_name='Region_A')df_data2 = pd.read_excel(excel_file_path, sheet_name='Region_B')
3.设置是否进行批量绘图,执行部分:
plot_all = True4.设置绘图结果的保存地址,绘图函数部分:
plt.savefig(fr'{scheme_id}.png', bbox_inches='tight', dpi=300)
推荐


获取方式
