Reputation: 825
I am trying to plot barplot using 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)
I want the bars to be sorted in descending order.Exercised_stock_options with highest value on left followed by total_stock_value and so on.
Kindly help.Thanks
Upvotes: 3
Views: 4350
Reputation: 339250
The two lines
pairs = zip(features_list[1:], scores) # zip with features_list
pairs= sorted(pairs, key=lambda x: x[1], reverse= True)
already give you a list of tuples, sorted by the scores
values. Now you only need to unzip it to two lists, which can be plotted.
newx, newy = zip(*pairs)
sns.barplot(x=newx, y=newy)
A full working example:
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()
Upvotes: 2