2

This is how I created the lists, originally from logistic regression coefs_ and their associated column labels.

#Create lists
column_labels = X.columns.tolist()
coef = logreg.coef_.squeeze().tolist()

# Zip together
labels_coef = list(zip(column_labels, coef))

#Sort them and present them as a list
sorted_labels = sorted(labels_coef, key=lambda x: x[1])

#Plotted the bar chart 
plt.barh(*zip(* sorted(sorted_labels[:5] +sorted_labels[-5:],key=lambda x: x[1] )))

#or
#plt.barh(*zip(* (sorted_labels[:5] +sorted_labels[-5:])))

#Show plot
plt.show()    

But how to print both of them on the same graph in ascending order of value?

Apparently, this does not do the trick

enter image description here

2 Answers2

1

Okay so after few days of work, I managed to get it to plot by sorting. There is a pre-step to @AndreyF answer, which using the itemgetter as a key on the operator. The code is as follows.

#This will output the top 5, and bottom 5 in sorted form

sorted(sorted_labels[:5], key=operator.itemgetter(1))
sorted(sorted_labels[-5:], key=operator.itemgetter(0))

#Then use the first part of @AndreyF answer

#plotting the list
labels, values = zip(*(sorted_labels[:5] +sorted_labels[-5:]))
plt.barh(range(len(labels)),values)
plt.yticks(range(len(values)),values)
plt.show()

enter image description here

0

you can append the first five and last five and plot them together:

 plt.barh(*zip(* (sorted_labels[:5] +sorted_labels[-5:])))

EDIT: The sorting isue was rased in this question:

Pyplot sorting y-values automatically

The 2 suggested solutions there were:

  1. plot data as numeric and add y_labels:
 labels, values = zip(*(sorted_labels[:5] +sorted_labels[-5:]))
    plt.barh(range(len(labels)),values)
    plt.yticks(range(len(values)),values)
    plt.show()
  1. Bypass the problem by using pandas's DataFrame:

    df = pd.DataFrame(list(zip(labels,values))).set_index(1)

    df.plot.barh()

AndreyF
  • 1,798
  • 1
  • 14
  • 25
  • it seems like you already sorted them here: `sorted_labels = sorted(labels_coef, key=lambda x: x[1])` – AndreyF Jan 25 '18 at 10:03
  • and if you'll plot and sort in the same line? `plt.barh(*zip(* sorted(sorted_labels[:5] +sorted_labels[-5:],key=lambda x: x[1] )))` – AndreyF Jan 25 '18 at 10:04
  • Check this https://stackoverflow.com/questions/47373762/pyplot-sorting-y-values-automatically – AndreyF Jan 25 '18 at 10:47
  • It now gets, 'NoneType' object has no attribute 'seq'. –  Jan 25 '18 at 12:19