如何在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
相关产品推荐
相关产品推荐

