Seaborn条形图订购 [英] Seaborn Bar Plot Ordering

查看:93
本文介绍了Seaborn条形图订购的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有两列的pandas数据框.

I have a pandas dataframe that has two columns.

我需要按计数"列排序的图.

I need the plot ordered by the "Count" Column.

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

现在,该图已按"Dim"列进行排序,我需要按"Count"列进行排序,该怎么办?

Right now the plot is getting ordered by the "Dim" column, I need it ordered by the "Count" column,How can I do this?

推荐答案

您必须以所需的方式对数据框进行排序,然后对其重新索引以创建新的升序/降序索引.之后,您可以绘制索引为x值的条形图.然后通过数据框的Dim列设置标签集:

You have to sort your dataframe in desired way and the reindex it to make new ascending / descending index. After that you may plot bar graph with index as x values. Then set set labels by Dim column of your dataframe:

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_values(['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()

这篇关于Seaborn条形图订购的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆