Python 2.7 DICT()和MATPLOTLIB?

Python 2.7 DICT()和MATPLOTLIB?,python-2.7,numpy,matplotlib,scikit-learn,sklearn-pandas,Python 2.7,Numpy,Matplotlib,Scikit Learn,Sklearn Pandas,我创建了一个字典,将sklearn中决策树的特性重要性与df中相应的特性名称相匹配。下面是代码: importances = clf.feature_importances_ feature_names = ['age','BP','chol','maxh', 'oldpeak','slope','vessels', 'sex_0.0','sex_1.0', 'pain_1.0','pain_2.0','pain_3.0'

我创建了一个字典,将sklearn中决策树的特性重要性与df中相应的特性名称相匹配。下面是代码:

   importances = clf.feature_importances_
   feature_names = ['age','BP','chol','maxh',
          'oldpeak','slope','vessels',
          'sex_0.0','sex_1.0', 
          'pain_1.0','pain_2.0','pain_3.0','pain_4.0',
          'bs_0.0','bs_1.0',
          'ecg_0.0','ecg_1.0','ecg_2.0',
          'ang_0.0','ang_1.0',
          'thal_3.0','thal_6.0','thal_7.0']
   CLF_sorted = dict(zip(feature_names, importances))
在输出中,我得到了以下结果:

   {'BP': 0.053673644739136502,
    'age': 0.014904980747733202,
    'ang_0.0': 0.0,
    'ang_1.0': 0.0,
    'bs_0.0': 0.0,
    'bs_1.0': 0.0,
    'chol': 0.11125922817930389, ...}
如我所料。我有两个问题要问你:

  • 我怎样才能创建一个条形图,其中x轴表示
    特征\u名称
    ,y轴表示相应的
    重要性

  • 如果可能,如何以降序方式对条形图进行排序

  • 试试这个:

    import pandas as pd
    
    df = pd.DataFrame({'feature': feature_names , 'importance': importances})
    df.sort_values('importance', ascending=False).set_index('feature').plot.bar(rot=0)
    
    演示:

    d={'BP':0.053673644739136502,
    “年龄”:0.014904980747733202,
    “ang_0.0”:0.0,
    “ang_1.0”:0.0,
    “bs_0.0”:0.0,
    “bs_1.0”:0.0,
    “chol”:0.11125922817930389}
    df=pd.DataFrame({'feature':[x代表d.keys()中的x,'importance':[x代表d.values()中的x})
    在[63]中:将matplotlib作为mpl导入
    在[64]中:mpl.style.use('ggplot')
    在[65]中:df.sort\u values('importance',升序=False)。set\u index('feature')。plot.bar(rot=0)
    出[65]:
    

    谢谢!我使用的是Python2.7,它返回的错误如下:“名称'd'未定义”。这个问题有什么解决办法吗?对不起,我的基本问题是,我一个月前才开始认真使用python。@ElenaPhys,尝试使用
    df=pd.DataFrame({'feature':feature\u names,'importance':importances})
    d
    -是您根据
    重要性
    功能名称
    @ElenaPhys创建的词典,有帮助吗?我如何设置绘图的大小?我阅读了pandas文档,但我只找到了调整条的方法。@ElenaPhys,当然,请尝试:
    .plot.bar(rot=0,figsize=(12,10))
    。打印函数继承matplotlib参数。。。
    d ={'BP': 0.053673644739136502,
        'age': 0.014904980747733202,
        'ang_0.0': 0.0,
        'ang_1.0': 0.0,
        'bs_0.0': 0.0,
        'bs_1.0': 0.0,
        'chol': 0.11125922817930389}
    
    df = pd.DataFrame({'feature': [x for x in d.keys()], 'importance': [x for x in d.values()]})
    
    In [63]: import matplotlib as mpl
    
    In [64]: mpl.style.use('ggplot')
    
    In [65]: df.sort_values('importance', ascending=False).set_index('feature').plot.bar(rot=0)
    Out[65]: <matplotlib.axes._subplots.AxesSubplot at 0x8c83748>