Seaborn barplot按长度排序

时间:2017-06-09 07:08:00

标签: python matplotlib bar-chart seaborn

我正在尝试使用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)

我的情节看起来像这样 enter image description here

我希望条形按降序排序.Exercised_stock_options左边是最高值,后面是total_stock_value,依此类推。

请帮助。谢谢

1 个答案:

答案 0 :(得分:2)

两行

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()

enter image description here