python - Seaborn 条形图排序

标签 python pandas matplotlib seaborn

我有一个包含两列的 Pandas 数据框。

我需要按“计数”列排序的图。

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”列排序,我该怎么做? enter image description here

最佳答案

您可以为此使用订单参数。

sns.barplot(x='Id', y="Speed", data=df, order=result['Id'])

感谢韦恩。

查看他的其余部分 code .

此链接对我仍然有效。但是,为了方便起见,我将作者的代码粘贴在这里。

result = df.groupby(["Id"])['Speed'].aggregate(np.median).reset_index().sort_values('Speed')
sns.barplot(x='Id', y="Speed", data=df, order=result['Id'])
plt.show()

df

   Id  Speed
0   1     30
1   1     35
2   1     31
3   2     20
4   2     25

结果

   Id   Speed
1   2   22.5
0   1   31.0
2   3   80.0

关于python - Seaborn 条形图排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43770507/

相关文章:

python - Pandas dataframe - 选择一列值包含字符串而另一列值以特定字符串开头的行

python - 如何在 seaborn ecdf 图上的 axhline 的交点上找到 x 值?

python - 动画改变点之间的线条数量 - Python

python - PDF 文件方向检测

python - 创建单行 Pandas 数据框

python - 在 Seaborn 中禁用色调嵌套

python - matplotlib.close() 不关闭绘图

python - 创建一个带有元素的 numpy 矩阵作为索引的函数

python - 如何将用户输入限制为 List 的元素

python - 刺槐。从 python 代码中读取 --host 值