如何按升序或降序对matplotlib图进行排序?

时间:2020-09-27 18:33:33

标签: python matplotlib

enter image description here
结果只是随机图,没有任何顺序。感谢您的帮助

importances = selector_clf.feature_importances_
std = np.std([tree.feature_importances_ for tree in 
selector_clf.estimators_],
         axis=0)

fig, ax = plt.subplots()


plt.rcParams["figure.figsize"] = [14,15]
plt.barh(range(len(predictors_tree)),std, color='lightgreen')
plt.ylabel("Predictors")
plt.xlabel("Importance")
plt.title("Importance Score")
plt.yticks(range(len(predictors_tree)), predictors_tree)
plt.show()

2 个答案:

答案 0 :(得分:0)

不同功能的重要性不能直接分类;您必须手动对其进行排序。可以使用np.sort(和np.argsort来完成,以便根据特征重要性标准差对预测树进行排序)。下面的代码应该可以解决问题。

importances = selector_clf.feature_importances_
std = np.std([tree.feature_importances_ for tree in 
selector_clf.estimators_],
         axis=0)

# Get sorted std and sorting index, and sort predictor tree
std_sorded = np.sort(std)
sorting_index = np.argsort(std)
predictor_tree = [predictor_tree[s] for s in sorting_index]

fig, ax = plt.subplots()


plt.rcParams["figure.figsize"] = [14,15]
plt.barh(range(len(predictors_tree)), std_sorded, color='lightgreen')
plt.ylabel("Predictors")
plt.xlabel("Importance")
plt.title("Importance Score")
plt.yticks(range(len(predictors_tree)), predictors_tree)
plt.show()

答案 1 :(得分:0)

看起来您的轴似乎并不相互依赖,所以我会在plt.barh之前对您的std数组进行排序

文档给出these examples

a = np.array([[1,4],[3,1]])
np.sort(a)                # sort along the last axis

#array([[1, 4],
#       [1, 3]])

np.sort(a, axis=None)     # sort the flattened array

#array([1, 1, 3, 4])

np.sort(a, axis=0)        # sort along the first axis

#array([[1, 1],
#       [3, 4]])

其中之一应该可以进行升序,然后可以使用np.flip进行降级。