Seaborn 条形图按条长排序

Seaborn barplot ordering by bar length

我正在尝试使用 seaborn 绘制条形图。

k= 'all'
k_best = SelectKBest(k=k)
k_best=k_best.fit(features, labels)
features_k=k_best.transform(features)
scores = k_best.scores_ # extract scores attribute
pairs = zip(features_list[1:], scores) # zip with features_list
pairs= sorted(pairs, key=lambda x: x[1], reverse= True) # sort tuples in descending order
print pairs

#Bar plot of features and its scores
sns.set(style="white")
ax = sns.barplot(x=features_list[1:], y=scores)
plt.ylabel('SelectKBest Feature Scores')
plt.xticks(rotation=90)

我的剧情是这样的

我希望条形图按 order.Exercised_stock_options 降序排列,最高值在左边,然后是 total_stock_value 等等。

敬请help.Thanks

两条线

pairs = zip(features_list[1:], scores) # zip with features_list
pairs= sorted(pairs, key=lambda x: x[1], reverse= True)

已经给你一个元组列表,按 scores 值排序。现在只需要解压成两个列表,就可以画出来了。

newx, newy = zip(*pairs)
sns.barplot(x=newx, y=newy)

一个完整的工作示例:

import seaborn.apionly as sns
import matplotlib.pyplot as plt

x = ["z","g","o"]
y = [5,7,4]

pairs = zip(x, y)
pairs= sorted(pairs, key=lambda x: x[1], reverse= True)

newx, newy = zip(*pairs)
ax = sns.barplot(x=newx, y=newy)

plt.show()