
代码绘制成果展示



代码解释


第一部分

# =========================================================================================# ====================================== 1. 库的导入 =========================================# =========================================================================================import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.colors import LinearSegmentedColormapfrom matplotlib.patches import Wedge, Patchfrom matplotlib.lines import Line2Dfrom scipy import statsimport matplotlibimport osmatplotlib.rcParams['pdf.fonttype'] = 42matplotlib.rcParams['ps.fonttype'] = 42plt.rcParams['font.family'] = 'Times New Roman'

第二部分

# =========================================================================================# ======================================2.颜色库设置=========================================# =========================================================================================COLOR_THEMES = {1: {'group_colors': {...}, 'heatmap_colors': [...], 'group_label_color': 'white'},}

第三部分

# =========================================================================================# ======================================3.绘图前需要做的准备=========================================# =========================================================================================#选择配色方案selected_scheme = 5#选择分析方法spearman, pearson,kendallselected_method = 'spearman'#输入文件的地址,输出结果的路径data_directory = r"E:\公众号素材\花瓣状热图"#每个数据文件的特征和目标data_slices = {'Flexural': {'features': slice(0, 16), 'targets': slice(16, 24)},'Flexural-shear': {'features': slice(0, 16), 'targets': slice(16, 24)},'Shear': {'features': slice(0, 16), 'targets': slice(16, 24)},'Bond': {'features': slice(0, 16), 'targets': slice(16, 24)}}#从颜色库里提取配色方案,如果没有就是用默认的颜色select_color = COLOR_THEMES.get(selected_scheme, 1)

第四部分

# =========================================================================================# ======================================4.绘图函数=========================================# =========================================================================================def create_full_ring_plot(all_data,all_feature_names,all_target_names,color_palette,sector_params, ):

第五部分

创建画布,设置颜色映射。
fig, ax = plt.subplots(figsize=(24, 24), subplot_kw={'aspect': 'equal'})ax.axis('off')heatmap_colors_value = color_palette['heatmap_colors']if isinstance(heatmap_colors_value, str):cmap = plt.get_cmap(heatmap_colors_value)else:cmap = LinearSegmentedColormap.from_list("custom_cmap", list(zip([0.0, 0.5, 1.0], heatmap_colors_value)))norm = plt.Normalize(vmin=-1, vmax=1)

第六部分

遍历每个数据分组,绘制对应的扇形区域
for idx, group_name in enumerate(group_names):features = all_feature_names[group_name]df, df_sig = all_data[group_name]['correlation_df'], all_data[group_name]['p_value_df']current_targets = all_target_names[group_name]start_angle_deg = sector_params[group_name]['start']end_angle_deg = sector_params[group_name]['end']theta_deg = np.linspace(start_angle_deg, end_angle_deg, len(features))theta_rad = np.deg2rad(theta_deg)angle_span_deg = abs(end_angle_deg - start_angle_deg) / len(features) * 0.95current_group_color = group_legend_colors[idx

第七部分

在每两个循环,先绘制出每一层,然后绘制每一层环上的每一个列的区域,然后在小区域的位置上面添加上相关性系数和显著性标记,在最外面的一圈上面加上特正名称的标注
for i, target_name in enumerate(current_targets):r_inner = radii[i]r_outer = radii[i] + 0.9values = df[target_name]sig_values = df_sig[target_name]cell_colors = cmap(norm(values))marker_angle_rad = np.deg2rad(sector_params[group_name]['marker_angle'])marker_radius = r_inner + 0.45for j in range(len(features)):ax.add_patch(wedge)text_angle_rad = theta_rad[j]text_radius = r_inner + 0.45x = text_radius * np.cos(text_angle_rad)y = text_radius * np.sin(text_angle_rad)sig_marker = '*' if sig_values.iloc[j] else ''text_val = f'{val:.2f}{sig_marker}'rot = theta_deg[j] - 90 if np.cos(text_angle_rad) > -0.01 else theta_deg[j] - 90label_radius = radii.max() + 1.7for i in range(len(features)):text_angle_rad = theta_rad[i]x = label_radius * np.cos(text_angle_rad)y = label_radius * np.sin(text_angle_rad)rot = theta_deg[i] if np.cos(text_angle_rad) > -0.01 else theta_deg[i] # - 180

第八部分

在中心的位置加上目标标记的图例,在主图的下面加上相关性数值大小的颜色条
group_label_angle_deg = (start_angle_deg + end_angle_deg) / 2group_label_angle_rad = np.deg2rad(group_label_angle_deg)group_label_radius = radii.max() + 4.5x = group_label_radius * np.cos(group_label_angle_rad)y = group_label_radius * np.sin(group_label_angle_rad)legend_positions = [{'bbox_to_anchor': (0.5, 0.5), 'loc': 'lower right'},{'bbox_to_anchor': (0.5, 0.5), 'loc': 'lower left'},{'bbox_to_anchor': (0.5, 0.5), 'loc': 'upper right'},{'bbox_to_anchor': (0.5, 0.5), 'loc': 'upper left'}]#遍历每个分组,为其单独创建图例for i, group_name in enumerate(group_names):#创建一个空列表,用于存放当前分组的图例句柄handles_for_group = []#获取当前分组的目标名称列表current_targets = all_target_names[group_name]#获取当前分组的标记的颜色current_group_color = group_legend_colors[i]#遍历当前分组的每个目标,为其创建图例项for j, target_name in enumerate(current_targets):handles_for_group.append(handle)leg.get_title().set_fontweight('bold')cax = fig.add_axes([0.2, 0.15, 0.6, 0.01]) # [左, 下, 宽, 高]sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)cbar = fig.colorbar(sm, cax=cax, orientation='horizontal')cbar.set_label("spearman", size=16)cbar.ax.tick_params(size=14, labelsize=14)

第九部分

def main():group_names = ['Flexural', 'Flexural-shear', 'Shear', 'Bond']sector_params = {group_names[0]: {'start': 100, 'end': 170, 'marker_angle': 175},group_names[1]: {'start': 10, 'end': 80, 'marker_angle': 85},group_names[2]: {'start': 280, 'end': 350, 'marker_angle': 355},group_names[3]: {'start': 190, 'end': 260, 'marker_angle': 265},}all_correlation_data = {}all_features_dict = {}generic_targets_dict = {}is_first_group = Truenum_features = 0num_targets = 0for group in group_names:feature_slice = data_slices[group]['features']target_slice = data_slices[group]['targets']excel_path = os.path.join(data_directory, f"{group}.xlsx")data = pd.read_excel(excel_path)feature_data = data.iloc[:, feature_slice]target_data = data.iloc[:, target_slice]current_features = data.columns[feature_slice].tolist()current_targets = data.columns[target_slice].tolist()all_features_dict[group] = current_featuresgeneric_targets_dict[group] = current_targetsif is_first_group:num_features = len(current_features)num_targets = len(current_targets)is_first_group = Falseelif len(current_features) != num_features or len(current_targets) != num_targets:print(f"文件 {excel_path} 的数据维度与第一个文件不匹配")del all_features_dict[group]del generic_targets_dict[group]continuefor i in range(num_features):for j in range(num_targets):feature_col_numeric = pd.to_numeric(feature_col, errors='coerce')target_col_numeric = pd.to_numeric(target_col, errors='coerce')combined = pd.concat([feature_col_numeric, target_col_numeric], axis=1).dropna()if len(combined) < 2:corr, p_value = np.nan, np.nanelse:if selected_method == 'spearman':corr, p_value = stats.spearmanr(combined.iloc[:, 0], combined.iloc[:, 1])elif selected_method == 'pearson':corr, p_value = stats.pearsonr(combined.iloc[:, 0], combined.iloc[:, 1])else:corr, p_value = stats.kendalltau(combined.iloc[:, 0], combined.iloc[:, 1])correlation_matrix[i, j] = corrp_value_matrix[i, j] = p_valuedf_corr = pd.DataFrame(correlation_matrix, index=current_features, columns=current_targets)df_sig = pd.DataFrame(p_value_matrix < 0.05, index=current_features, columns=current_targets)print("\n相关性系数:")print(df_corr.to_string())print("\n显著性:")print(df_sig.to_string())all_correlation_data[group] = {'correlation_df': df_corr,'p_value_df': df_sig}create_full_ring_plot(all_data=all_correlation_data,all_feature_names=all_features_dict,all_target_names=generic_targets_dict,color_palette=select_color,sector_params=sector_params,)

如何应用?

1.选择配色方案:
selected_scheme = 392.选择分析方法:
selected_method = 'spearman'3.设置文件夹的位置:
data_directory = r"E:\公众号素材\花瓣状热图"4.设置文件名、特征列、目标列:
data_slices = {'Flexural': {'features': slice(0, 16), 'targets': slice(16, 24)},'Flexural-shear': {'features': slice(0, 16), 'targets': slice(16, 24)},'Shear': {'features': slice(0, 16), 'targets': slice(16, 24)},'Bond': {'features': slice(0, 16), 'targets': slice(16, 24)}}
5.设置文件名(目标名):
group_names = ['Flexural', 'Flexural-shear', 'Shear', 'Bond']
推荐


预告









获取方式
