我遇到了有关按其特征对我的特征进行排序的问题。我希望看到我的图像随着y轴上的高条变得越来越短。不幸的是,我的条形图看起来像这样,其功能按字母顺序排序:
现在我正在运行以下代码:
unsorted_list = [(importance, feature) for feature, importance in
zip(features, importances)]
sorted_list = sorted(unsorted_list)
features_sorted = []
importance_sorted = []
for i in sorted_list:
features_sorted += [i[1]]
importance_sorted += [i[0]]
plt.title("Feature importance", fontsize=15)
plt.xlabel("Importance", fontsize=13)
plt.barh(features_sorted,importance_sorted, color="green", edgecolor='green')
# plt.savefig('importance_barh.png', dpi=100)
以下是那里的数据:
unsorted_list =
[('HR', 0.28804817462980353),
('BR', 0.04062328177704225),
('Posture', 0.09011618483921582),
('Activity', 0.0017821837085763366),
('PeakAccel', 0.002649111136700579),
('HRV', 0.13598729040097057),
('ROGState', 0.014534726412631642),
('ROGTime', 0.22986192060475388),
('VerticalMin', 0.016099772399198357),
('VerticalPeak', 0.012697214182994502),
('LateralMin', 0.029479112475744584),
('LateralPeak', 0.022745210003295983),
('SagittalMin', 0.08653071485979484),
('SagittalPeak', 0.028845102569277088)]
sorted_list =
[(0.0017821837085763366, 'Activity'),
(0.002649111136700579, 'PeakAccel'),
(0.012697214182994502, 'VerticalPeak'),
(0.014534726412631642, 'ROGState'),
(0.016099772399198357, 'VerticalMin'),
(0.022745210003295983, 'LateralPeak'),
(0.028845102569277088, 'SagittalPeak'),
(0.029479112475744584, 'LateralMin'),
(0.04062328177704225, 'BR'),
(0.08653071485979484, 'SagittalMin'),
(0.09011618483921582, 'Posture'),
(0.13598729040097057, 'HRV'),
(0.22986192060475388, 'ROGTime'),
(0.28804817462980353, 'HR')]
我最近升级到了matplotlib 3.0.2
提前感谢您的帮助!
答案 0 :(得分:2)
编辑(基于评论)
您的代码在matplotlib 2.2.2
上运行良好,问题似乎出在您的列表命名约定以及它们之间的某些混淆上。它完全可以在3.0.2预期。不过,您可能有兴趣了解解决方法
features_sorted = []
importance_sorted = []
for i in sorted_list:
features_sorted += [i[1]]
importance_sorted += [i[0]]
plt.title("Feature importance", fontsize=15)
plt.xlabel("Importance", fontsize=13)
plt.barh(range(len(importance_sorted)), importance_sorted, color="green", edgecolor='green')
plt.yticks(range(len(importance_sorted)), features_sorted);
由@tmdavison推荐的替代方法
plt.barh(range(len(importance_sorted)), importance_sorted, color="green",
edgecolor='green', tick_label=features_sorted)
答案 1 :(得分:0)