gpt4 book ai didi

python - 按 matplotlib 中的列表值对条形图进行排序

转载 作者:行者123 更新时间:2023-12-01 01:15:11 24 4
gpt4 key购买 nike

我遇到了有关按功能值排序的问题。我希望看到我的图像,其中条形根据 y 轴上的高度而变短。不幸的是,我的条形图如下所示,功能按字母顺序排序:

enter image description here

现在我正在运行以下代码:

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

最佳答案

编辑(根据评论)

您的代码在 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);

enter image description here

@tmdavison 建议的替代方案

plt.barh(range(len(importance_sorted)), importance_sorted, color="green", 
edgecolor='green', tick_label=features_sorted)

关于python - 按 matplotlib 中的列表值对条形图进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54424256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com