当前位置:首页>python>期刊图片复现|Python绘制圆环状火柴棒图+热图组合图

期刊图片复现|Python绘制圆环状火柴棒图+热图组合图

  • 2026-10-11 07:53:49
期刊图片复现|Python绘制圆环状火柴棒图+热图组合图

代码绘制成果展示

论文:Closing maize yield gaps in North China plain: Based on plot-scale farmer  survey and simulation

论文原图
此图最外围的数字代表每一个独立样本的ID编号;外侧的三层火柴棒图分别展示了各个样本在“Age”、“Education”和“Area”三个连续型变量上的具体数值,线段越长代表数值越大,环的起始切口处附有对应的刻度;最内侧的两层实心扇形色环则通过不同的颜色映射,直观展现了对应样本在“Training”和“Machines”这两个分类变量上的归属情况。在图左上角的留白区域,内嵌了五组全局统计子图,其中三个结合了抖动散点的透明箱线图,详细剖析了“Age”、“Education”和“Area”三个连续变量在整体数据中的集中趋势、离散程度及分布极值(背景带有带状刻度标签);其右侧的两个带有具体数值标注的堆叠柱状图,则精准统计并展示了“Training”和“Machines”在总样本中所占的百分比比例;最后,位于圆环内部中心处的图例,为所有连续变量颜色及分类标签提供了颜色对照基准。
仿图
多种配色

代码解释

第一部分

库的导入以及字体设置
# =========================================================================================# ====================================== 1. 环境设置 =======================================# =========================================================================================import numpy as npimport pandas as pdimport matplotlib.pyplot as plt

第二部分

颜色库
# =========================================================================================# ======================================2.颜色库=======================================# =========================================================================================color_schemes = {    1: {'Age': '#691F73', 'Education': '#FF5000', 'Area': '#0062A5', 'Train_Yes': '#E22510', 'Train_No': '#E4B66B',        'Mach_1': '#00584D', }

第三部分

绘图函数:配色方案提取,主画布创建,圆环半径、角度等设计
# =========================================================================================# ======================================3.绘图函数=======================================# =========================================================================================def create_plot(df, n, scheme_id=1, ring_thickness=0.8, ring_gap=0.2):    colors = color_schemes.get(scheme_id, color_schemes[1])  #提取配色方案    #创建画布    fig = plt.figure(figsize=(14, 14), facecolor='white')    ax = fig.add_axes([0, 0, 1, 1])  #添加轴    ax.set_aspect('equal')  #设置x轴和y轴的比例一致    ax.axis('off')  #关闭坐标轴线条、刻度和标签    total_radians = 1.5 * np.pi  #圆环站的角度    d_theta = total_radians / n  #每个样本的角度区间大小    thetas = np.linspace(np.pi / 2 - d_theta / 2, -np.pi + d_theta / 2, n)  #所有样本中心角度

第四部分

绘图函数:绘制内侧的两个分类型热图的扇形色块
    #扇形色块的绘制函数    def draw_wedge(ax, r_in, r_out, t_start, t_end, color):        ax.fill(x,  #x                y,  #y                color=color,  #填颜色                edgecolor='black',  #边框色                lw=0.3)  #边框线宽        draw_wedge(ax, rings['Machines'][0], rings['Machines'][1], t_start, t_end, m_col)        t_col = colors['Train_Yes'] if df['Training'].iloc[i] == 1 else colors['Train_No'] #映射颜色        #绘制第二层扇形色块        draw_wedge(ax, rings['Training'][0], rings['Training'][1], t_start, t_end, t_col)

第五部分

绘图函数:绘制外侧3层连续型数值数据的火柴棒图
    #遍历外层火柴棒环名称、数据列名、数据范围和刻度信息    for ring_name, data_col, v_lims, ring_ticks in zip(            ['Area', 'Education', 'Age'],  #圆环名            ['Area', 'Education', 'Age'],  #数据列名            [(0, 1.5), (-2, 17), (20, 80)],  #数据范围            #刻度值            [[0.3, 0.6, 1.0, 1.3],             [0, 5, 10, 15],             [30,  50, 70]]):            ax.plot(x_box,  #x                    y_box,  #y                    color='black',  #颜色                    lw=0.6,  #线宽                    zorder=0)  #层            val = df[data_col].iloc[i]  #提取当前样本在该指标下的具体数值            r_val = r_in + (val - v_lims[0]) / (v_lims[1] - v_lims[0]) * (r_out - r_in)  #将该数值映射到该圆环内的特定半径上            #绘制火柴棒线部分            ax.plot([r_in * np.cos(t_center), r_val * np.cos(t_center)],  #x                    [r_in * np.sin(t_center), r_val * np.sin(t_center)],  #y                    color=colors[ring_name],  #颜色                    lw=1.5, #线宽                    zorder=1)  #层            #点部分            ax.plot(r_val * np.cos(t_center),  #x                    r_val * np.sin(t_center),  #y                    'o',  #样式                    color=colors[ring_name],  #颜色                    markersize=4,  #大小                    zorder=2)  #层

第六部分

绘图函数:遍历绘制出最外圈的标注
    text_radius = rings['Age'][1] + 0.4  #外圈文本标注半径    #遍历所有样本数据添加ID文本        ax.text(x_text,  #x                y_text,  #y                str(df['ID'].iloc[i]),  #文本                rotation=rot_deg,  #旋转                ha='center',  #水平                va='center',  #垂直                fontsize=13)  #字体大小

第七部分

绘图函数:绘制左上角的箱线图+散点图的组合图
    #箱型图和散点图组合图绘制函数    def create_vertical_swarm(ax_sub, data, color, title, unit, ylim, ticks):        ax_sub.set_ylim(ylim)  #y轴范围        #标题        ax_sub.set_title(f"{title}\n({unit})",fontsize=16,pad=10)        ax_sub.set_xticks([])  #隐藏x轴刻度        ax_sub.set_yticks([])  #隐藏y轴刻度        ax_sub.set_ylabel('')  #y轴标题        #设置边框        for spine in ax_sub.spines.values():            spine.set_color('gray')  #颜色            spine.set_linewidth(0.5)  #宽度                        zorder=3,  #层                        #背景框属性                        bbox=dict(facecolor='#6d6a5d',  #背景颜色                                  edgecolor='none',  #背景框线                                  pad=1.5,  #背景框的内边距                                  alpha=0.8))  #透明度    #创建Age箱线图轴    ax_age = ax.inset_axes([-rings['Age'][1],  #x                            0.2,  #y                            ring_thickness, 8.0],  #宽度高度                           transform=ax.transData)  #坐标系    #绘制    create_vertical_swarm(ax_age,  #轴                          df['Age'],  #数据                          colors['Age'],  #颜色                          'Age',  #标题                          'years',  #单位                          [20, 80],  #y轴范围                          [30, 40, 50, 60, 70])  #刻度    #Education    ax_edu = ax.inset_axes([-rings['Education'][1], 0.2, ring_thickness,8.0],transform=ax.transData)    create_vertical_swarm(ax_edu, df['Education'],colors['Education'], 'Education', 'years',[-2, 17],[0, 5, 10, 15])    ax_area = ax.inset_axes([-rings['Area'][1],0.2,ring_thickness, 8.0],transform=ax.transData)    create_vertical_swarm(ax_area,df['Area'],colors['Area'], 'Area','ha', [0, 1.5],[0.3, 0.6, 1.0, 1.3])

第八部分

绘图函数:绘制左上角堆叠柱状图
    ax_train = ax.inset_axes([-rings['Training'][1],0.2,  ring_thickness,8.0],transform=ax.transData)    train_counts = df['Training'].value_counts(normalize=True) * 100  #转换为百分数    t_0 = train_counts.get(0, 0)  #0的百分比    t_1 = train_counts.get(1, 0)  #1的百分比    if t_1 > 5:        ax_train.text(0,  #x                      t_0 + t_1 / 2,  #y                      f"{t_1:.1f}",  #文本                      ha='center',  #水平                      va='center',  #垂直                      color='white',  #颜色                      fontsize=16)  #大小    #标题    ax_train.set_title("Training(%)",  #文本                       rotation=45,  #旋转                       ha='left',  #水平                       y=1.02,  #y                       fontsize=16)  #大小    ax_train.axis('off')  #去掉边框与轴线    ax_train.set_ylim(0, 100)  #y轴范围    #插入子图轴    ax_mach = ax.inset_axes([-rings['Machines'][1], 0.2, ring_thickness, 8.0], transform=ax.transData)    mach_counts = df['Machines'].value_counts(normalize=True) * 100  #百分比        btm += p  #更新    #标题    ax_mach.set_title("Machines(%)",  #文本                      rotation=45,  #旋转                      ha='left',  #水平                      y=1.02,  #y                      fontsize=16)  #大小    ax_mach.axis('off')  #去掉边框、坐标刻度    ax_mach.set_ylim(0, 100)  #y轴范围

第九部分

绘图函数:绘制自定义的图例以及绘图结果保存
    ax_leg = ax.inset_axes([-1.8, -1.5, 3.6, 3.0], transform=ax.transData)  #图例轴    ax_leg.axis('off')  #去掉轴显示    ax_leg.set_xlim(0, 3.6)  #x范围    ax_leg.set_ylim(0, 3.0)  #y范围           facecolor=colors['Age']))  #填充色    #    ax_leg.text(0.4,  #x                2.7,  #y                'Age',  #文本                va='center',  #垂直                fontsize=14)  #大小    ax_leg.add_patch(Rectangle((0.0, 1.0),w,h, facecolor=colors['Train_No']))    ax_leg.text(0.4,1.1,'0',va='center',fontsize=14)    ax_leg.text(1.4,2.0,'Machines',va='center',fontsize=14)    #配置颜色    m_list = [colors['Mach_1'],              colors['Mach_2'],              colors['Mach_3'],              colors['Mach_4'],              ]

第十部分

绘图函数:绘制自定义的图例以及绘图结果保存
# =========================================================================================# ======================================4.执行部分=======================================# =========================================================================================if __name__ == "__main__":    RING_THICKNESS = 1.3  #圆环厚度    RING_GAP = 0.2  #圆环间隔    df_real_data = pd.read_excel(r'data.xlsx')  #读取数据    n = len(df_real_data)  #样本数用于划分圆环区域    #设置是否批量绘图    plot_all = True    if plot_all:        for i in color_schemes.keys():            create_plot(df_real_data, n, scheme_id=i, ring_thickness=RING_THICKNESS,ring_gap=RING_GAP)    else:        TARGET_SCHEME = 1        create_plot(df_real_data, n, scheme_id=TARGET_SCHEME, ring_thickness=RING_THICKNESS,ring_gap=RING_GAP)

如何应用到你自己的数据

1.设置原始数据的保存路径,执行部分:

df_real_data = pd.read_excel(r'data.xlsx')  #读取数据

2.提取热图部分数据映射颜色,绘图函数部分:

m_col = [colors['Mach_1'], colors['Mach_2'], colors['Mach_3'], colors['Mach_4']][df['Machines'].iloc[i] - 1]  

3.定义连续型数据列名,绘图函数部分:

['Area', 'Education', 'Age'],  #数据列名

4.定义绘图结果的保存地址,绘图函数部分:

plt.savefig(fr'plot_{scheme_id}.png', dpi=300,bbox_inches='tight')

推荐

期刊图片复现|Python绘制二维偏依赖PDP图
期刊复现|python绘制基于SHAP分析和GAM模型拟合的单特征依赖图
期刊图片复现|python绘制带有渐变颜色shap特征重要性组合图(条形图+蜂巢图)
期刊复现|用Python绘制SHAP特征重要性总览图、依赖图、双特征交互效应SHAP图,解锁XGBoost模型的终极奥秘
期刊图片复现|Python绘制shap重要性蜂巢图+单特征依赖图+交互效应强度气泡图+交互效应依赖图(回归+二分类+分类)

获取方式

公众号中的所有所有的免费代码都已经下架了,都并入到付费部分里了,付费合集代码和数据的购买通道已经开通,全部合集100元,后续将会持续更新,决定购买请后台私信我,注意只会分享练习数据和代码文件,不会提供答疑服务,代码文件中已经包含了每行代码的完整注释,购买前请确保真的需要!!!

最新文章

随机文章