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

如何在Python中将Matplotlib绘图的X/Y轴刻度转为元组列表?

提取Matplotlib绘图中的特征名称与系数并导出CSV

问题描述

我希望在Python中将Matplotlib绘图的X轴刻度(特征名称)和Y轴刻度(特征值,即SVM的系数)转换为元组列表,最终将这些配对导出为CSV文件。以下是我的绘图代码:

from sklearn import svm
import matplotlib.pyplot as plt
import numpy as np

def feature_plot(classifier, feature_names, top_features=25):
    coef = classifier.coef_.ravel()
    top_positive_coefficients = np.argsort(coef)[-top_features:]
    # top_negative_coefficients = np.argsort(coef)[:top_features]
    # top_coefficients = np.hstack([top_negative_coefficients, top_positive_coefficients])
    plt.figure(figsize=(18, 7))
    colors = ['green' if c < 0 else 'blue' for c in coef[top_positive_coefficients]]
    plt.bar(np.arange(top_features), coef[top_positive_coefficients], color=colors)
    feature_names = np.array(feature_names)
    plt.xticks(np.arange(top_features), feature_names[top_positive_coefficients], rotation=45, ha='right')
    plt.show()

# print(pandasdfx.drop(columns=['target_label'], axis = 1).columns.values)

trainedsvm = svm.LinearSVC(C=0.001, max_iter=10000, dual=False).fit(Xx_train2, yx_train)
feature_plot(trainedsvm, pandasdfx.drop(columns=['target_label'], axis = 1).columns.values)

解决方案

不需要从已绘制的Matplotlib图表中提取刻度数据,直接在生成绘图数据的阶段就可以获取特征名称与对应系数的配对,这样更准确高效。下面是修改后的代码:

修改后的feature_plot函数

from sklearn import svm
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd  # 用于导出CSV,也可以用内置csv模块

def feature_plot(classifier, feature_names, top_features=25, save_csv_path='特征系数配对.csv'):
    coef = classifier.coef_.ravel()
    top_positive_coefficients = np.argsort(coef)[-top_features:]
    feature_names = np.array(feature_names)
    
    # 生成特征名称与系数的配对元组列表
    feature_coef_pairs = list(zip(feature_names[top_positive_coefficients], coef[top_positive_coefficients]))
    
    # 绘图部分保持不变
    plt.figure(figsize=(18, 7))
    colors = ['green' if c < 0 else 'blue' for c in coef[top_positive_coefficients]]
    plt.bar(np.arange(top_features), coef[top_positive_coefficients], color=colors)
    plt.xticks(np.arange(top_features), feature_names[top_positive_coefficients], rotation=45, ha='right')
    plt.show()
    
    # 导出为CSV文件
    df = pd.DataFrame(feature_coef_pairs, columns=['特征名称', '系数值'])
    df.to_csv(save_csv_path, index=False, encoding='utf-8-sig')
    print(f"已成功导出CSV文件至:{save_csv_path}")

# 训练模型并调用函数
trainedsvm = svm.LinearSVC(C=0.001, max_iter=10000, dual=False).fit(Xx_train2, yx_train)
feature_plot(trainedsvm, pandasdfx.drop(columns=['target_label'], axis=1).columns.values)

关键说明

  • 直接获取配对数据:利用top_positive_coefficients索引,直接从原始的feature_names和coef数组中提取对应的数据,组成元组列表feature_coef_pairs,避免从Matplotlib对象中解析刻度可能带来的格式问题。
  • CSV导出方式:
    • 示例中使用pandas的to_csv方法,操作简洁,支持自定义列名和编码(utf-8-sig确保中文在Excel中正常显示)。
    • 如果不想依赖pandas,可以用Python内置的csv模块替代:
      import csv
      with open(save_csv_path, 'w', newline='', encoding='utf-8-sig') as f:
          writer = csv.writer(f)
          writer.writerow(['特征名称', '系数值'])  # 写入表头
          writer.writerows(feature_coef_pairs)  # 写入所有配对数据
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:50:17