Skip to main content
 首页 » 编程设计

python之如何在 python 中的同一图形上以升序绘制压缩列表的前 5 和后 5

2025年01月19日8luoye11

这就是我创建列表的方式,最初来自逻辑回归 coefs_ 及其关联的列标签。

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

但是如何将它们按值的升序打印在同一个图表上呢?

显然,这并不能解决问题

请您参考如下方法:

好的,经过几天的工作,我设法通过排序来绘制它。 @AndreyF 回答有一个前置步骤,它使用 itemgetter 作为运算符的键。代码如下。

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