2017-05-03 59 views
3

我有一個有兩列的熊貓數據框。Seaborn條形圖訂購

我需要按「計數」列排序的圖。

dicti=({'37':99943,'25':47228,'36':16933,'40':14996,'35':11791,'34':8030,'24' : 6319 ,'2' :5055 ,'39' :4758 ,'38' :4611 }) 
pd_df = pd.DataFrame(list(dicti.iteritems())) 
pd_df.columns =["Dim","Count"] 
plt.figure(figsize=(12,8)) 
ax = sns.barplot(x="Dim", y= "Count",data=pd_df) 
ax.get_yaxis().set_major_formatter(plt.FuncFormatter(lambda x, loc: " 
{:,}".format(int(x)))) 
ax.set(xlabel="Dim", ylabel='Count') 
for item in ax.get_xticklabels(): 
    item.set_rotation(90) 
for i, v in enumerate(pd_df["Count"].iteritems()):   
    ax.text(i ,v[1], "{:,}".format(v[1]), color='m', va ='bottom', 
    rotation=45) 
plt.tight_layout() 

現在情節是由「昏暗」列有序,我需要它按「計數」列排序,我該怎麼做? enter image description here

+1

你看過了'barplot'的文檔?它需要一個名爲'order'的參數。所以你可以按你的「Count」列進行排序,並將生成的Dim值傳遞給它。 –

回答

2

您必須按照所需的方式對數據幀進行排序,並使其重新索引以創建新的升序/降序索引。之後,您可以繪製索引爲x值的條形圖。然後設置標籤集中你的數據框的點心列:

import matplotlib.pylab as plt 
import pandas as pd 
import seaborn as sns 

dicti=({'37':99943,'25':47228,'36':16933,'40':14996,'35':11791,'34':8030,'24' : 6319 ,'2' :5055 ,'39' :4758 ,'38' :4611 }) 
pd_df = pd.DataFrame(list(dicti.items())) 
pd_df.columns =["Dim","Count"] 
print (pd_df) 
# sort df by Count column 
pd_df = pd_df.sort(['Count']).reset_index(drop=True) 
print (pd_df) 

plt.figure(figsize=(12,8)) 
# plot barh chart with index as x values 
ax = sns.barplot(pd_df.index, pd_df.Count) 
ax.get_yaxis().set_major_formatter(plt.FuncFormatter(lambda x, loc: "{:,}".format(int(x)))) 
ax.set(xlabel="Dim", ylabel='Count') 
# add proper Dim values as x labels 
ax.set_xticklabels(pd_df.Dim) 
for item in ax.get_xticklabels(): item.set_rotation(90) 
for i, v in enumerate(pd_df["Count"].iteritems()):   
    ax.text(i ,v[1], "{:,}".format(v[1]), color='m', va ='bottom', rotation=45) 
plt.tight_layout() 
plt.show() 

enter image description here

+0

我是否正確地理解了它 - 即使我已經對數據框進行了排序,我也必須首先使用索引作爲標籤來創建它,以確保sns不會根據標籤名稱按字母順序對條形圖進行排序(並且無法傳遞,例如' sorted = False',爲了避免這種情況)? – Rotkiv

+0

我想你必須測試它 – Serenity