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

Python脚本中Shap汇总图特征显示异常问题求助

Shap汇总图特征显示在底部而非侧边的问题解决

问题场景

在Python脚本(非Notebook)中保存Shap汇总图时,生成的图表特征标签显示在底部,而非预期的侧边(y轴位置),使用的代码如下:

summary_plot = shap.summary_plot(shap_values, sample_df , show=False)
plt.savefig('temp3.png',format = "png",dpi = 150,bbox_inches = 'tight')

原因及解决方法

  • 显式指定布局方向:shap.summary_plot默认的散点汇总图(plot_type="dot")本应为横向布局(特征在y轴侧边),但非交互式脚本环境中可能因自动布局调整导致特征轴移位。显式指定orientation="horizontal"可强制保持特征在侧边:

    # summary_plot无返回值,无需赋值给变量
    shap.summary_plot(shap_values, sample_df, show=False, orientation="horizontal")
    plt.savefig('temp3.png', format="png", dpi=150, bbox_inches='tight')
    
  • 条形图的专属设置:如果目标是保存条形图,需显式指定plot_type="bar",该类型默认将特征放在侧边(y轴),无需额外调整方向:

    shap.summary_plot(shap_values, sample_df, plot_type="bar", show=False)
    plt.savefig('temp_bar.png', format="png", dpi=150, bbox_inches='tight')
    
  • 解决后端布局冲突:在非Notebook脚本中,可提前指定matplotlib的非交互式后端,避免交互逻辑导致的布局异常:

    import matplotlib.pyplot as plt
    plt.switch_backend('Agg')  # 绘图前设置
    import shap
    
    shap.summary_plot(shap_values, sample_df, show=False, orientation="horizontal")
    plt.savefig('temp3.png', format="png", dpi=150, bbox_inches='tight')
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:35:13