You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pygam的部分依赖图X轴添加rug plot(数据点密度刻度)

在pygam的部分依赖图中添加Rug Plot

pygam没有内置的rug plot功能,但可以通过matplotlib的rug()方法手动实现,只需要用到训练模型时的原始特征数据。以下是修改后的完整代码:

# gam model code above
# 假设你的训练数据存储在变量X_train中(替换为你实际的变量名)

# PLOT TRIAL

# Set up the figure
titles = ['1','2','3','4','5','6','7', '8', '9', '10', '11', '12']
fig, axs = plt.subplots(nrows=4, ncols=3, figsize=(20, 20), layout='constrained')
axs = axs.flatten()

# Make the partial dependence plots.
for i in range(0,12,1):
    XX = gam.generate_X_grid(term=i)
    # 绘制主部分依赖曲线和置信区间
    axs[i].plot(XX[:, i], gam.partial_dependence(term=i, X=XX), c='dimgrey', ls='solid', lw=2)
    axs[i].plot(XX[:, i], gam.partial_dependence(term=i, X=XX, width=.95)[1], c='cornflowerblue', ls='dotted',lw=1.5)
    
    # 添加Rug Plot:提取当前变量的原始数据点
    x_vals = X_train[:, i]  # 如果是DataFrame格式,改用X_train.iloc[:, i]
    axs[i].rug(x_vals, color='darkgray', alpha=0.5, linewidth=0.8)
    
    # 原有格式设置
    axs[i].set_ylim(-2,2)
    axs[i].set_xlabel(titles[i], fontsize=12)
    axs[i].set_ylabel("Partial Effect", fontsize=12)
    axs[i].set_title("")
    axs[i].axhline(y=0.0, c="crimson",linewidth=0.6,zorder=0,ls=':')

fig.savefig('partial_plot_from_python.eps', format='eps', dpi=600)

关键说明:

  • 务必将X_train替换为你训练GAM模型时使用的真实特征数据变量名
  • 设置alpha=0.5是为了降低rug线条的透明度,避免遮挡主依赖曲线
  • 可根据需求调整color和linewidth参数,让rug plot与图表风格更协调
  • 分类变量的rug plot参考价值较低,建议仅在连续变量的子图中添加该元素

内容的提问来源于stack exchange,提问作者Reading

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 07:18:09