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

如何将Matplotlib中模型特征重要性堆叠条形图改为并列显示?

解决决策树特征重要性并列水平条形图重叠问题

问题核心

原代码存在三个关键问题:

  • 两个模型的特征各自独立排序,导致同一特征在y轴位置不对应
  • 两个条形图使用完全相同的y轴坐标,直接重叠
  • 错误使用twinx()创建双x轴,引发绘图冲突

修改后的代码

import matplotlib.pyplot as plt
import numpy as np

def plot_importances1(model1, feature_names1, label1, model2=None, feature_names2=None, label2=None):
    if model2 is None:
        importances1 = model1.feature_importances_
        indices1 = np.argsort(importances1)

        plt.figure(figsize=(8, 8))
        plt.barh(range(len(indices1)), importances1[indices1], color="violet", align="center", label=label1)
        plt.yticks(range(len(indices1)), [feature_names1[i] for i in indices1])
        plt.title("Feature Importances")
        plt.xlabel("Relative Importance")
        plt.ylabel("Feature")
        plt.legend()
        plt.show()
    else:
        # 统一特征排序逻辑:以第一个模型的排序结果为准,保证特征位置对应
        importances1 = model1.feature_importances_
        indices1 = np.argsort(importances1)
        sorted_features = [feature_names1[i] for i in indices1]
        
        # 对齐第二个模型的重要性顺序,匹配第一个模型的特征列表
        importances2 = model2.feature_importances_
        # 假设两个模型特征列表完全一致,不一致时需额外处理特征交集/补全
        indices2 = [feature_names2.index(f) for f in sorted_features]
        sorted_importances2 = importances2[indices2]
        
        plt.figure(figsize=(10, 8))
        bar_width = 0.35  # 设定条形宽度
        y_pos = np.arange(len(sorted_features))  # 基础y轴位置
        
        # 两个条形分别向左右偏移,实现并列
        plt.barh(y_pos - bar_width/2, importances1[indices1], bar_width, color="violet", label=label1)
        plt.barh(y_pos + bar_width/2, sorted_importances2, bar_width, color="orange", label=label2)
        
        # 将y轴刻度设置在两个条形的中间位置
        plt.yticks(y_pos, sorted_features)
        plt.title("Feature Importances Comparison")
        plt.xlabel("Relative Importance")
        plt.ylabel("Feature")
        plt.legend()
        plt.tight_layout()  # 自动调整布局,避免标签截断
        plt.show()

关键修改点说明

  • 特征顺序对齐:强制第二个模型的重要性按照第一个模型的特征排序结果匹配,确保同一特征在y轴同一位置
  • 条形偏移实现并列:通过y_pos ± bar_width/2让两个条形在同一y坐标下左右分开,彻底解决重叠问题
  • 移除冗余双x轴:删除twinx()相关代码,单x轴即可满足对比需求,消除绘图报错
  • 布局优化:添加plt.tight_layout()自动调整元素位置,避免标签或图例被截断

调用示例

plot_importances1(
    dTree_treat_out,
    list(X1_train),
    "Outliers present",
    dTree,
    list(X_train),
    "No outliers",
)

注意:若两个模型的特征列表不完全一致,需额外处理特征匹配逻辑,比如取特征交集或为缺失特征填充0值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:50:13