繁体   English   中英

通过升序或降序对 python Seaborn 条形图进行排序

[英]Ordering a python Seaborn barplot by ascending or descending

这是我当前的代码,使用美国境内死亡原因的发生次数数据集:

`top_cause_of_death_barplot=sns.catplot(data=death, x='cause_name', 
y='deaths',kind='bar',ci=None,legend_out=False,height=10, aspect=1.5)
plt.xlabel('Causes of Death',fontsize=15)
top_cause_of_death_barplot.set_xticklabels(fontsize=10)
plt.ylabel('Number of Observed Deaths',fontsize=15)
plt.title('Top Ten Leading Causes of Death in the United States (1999-2017)',fontsize=20)`

这会产生一个看起来像这样的图表: 原始代码

我试图重新排序图表,使条形按降序排列。 我在我的代码中添加了一点并得到了这个:

`result = death.groupby(["cause_name"]) 
['deaths'].aggregate(np.median).reset_index().sort_values('cause_name')
top_cause_of_death_barplot=sns.catplot(data=death, x='cause_name', 
y='deaths',kind='bar',ci=None,legend_out=False,height=10, aspect=1.5, order=result['cause_name'] )
plt.xlabel('Causes of Death',fontsize=15)
top_cause_of_death_barplot.set_xticklabels(fontsize=10)
plt.ylabel('Number of Observed Deaths',fontsize=15)
plt.title('Top Ten Leading Causes of Death in the United States (1999-2017)',fontsize=20)`

虽然这段代码没有给我任何错误,但它似乎只是以不同的随机顺序重新排列条形,如下所示:

代码版本 2 结果

为什么会发生这种情况? 我做错了什么,是否有某种方法可以将条形重新排列为我不知道的升序或降序?

您必须将x=值传递给order= 在你的情况下,我会这样做:

death = pd.read_csv('https://storage.googleapis.com/hewwo/NCHS_-_Leading_Causes_of_Death__United_States.csv', sep=',', header=0)

plot_order = death.groupby('Cause Name')['Deaths'].sum().sort_values(ascending=False).index.values

sns.catplot(data=death, x='Cause Name',  y='Deaths',kind='bar',ci=None, legend_out=False, order=plot_order)

在此处输入图片说明

或者,如果您想删除“所有原因”栏:

sns.catplot(data=death, x='Cause Name',  y='Deaths',kind='bar',ci=None, legend_out=False, order=plot_order[1:])

在此处输入图片说明

您可以将sns.catplot()order参数设置为您喜欢的顺序。 您可以使用df['col'].value_counts().index来获取此订单。 您尚未提供数据示例,因此请允许我提供一个易于重现的示例。

import seaborn as sns
import pandas as pd
import numpy as np

a = np.random.choice(['cat', 'dog', 'hamster'], 100)

df = pd.DataFrame(a, columns=['animals'])

sns.catplot(data=df, x='animals',kind='count',ci=None,legend_out=False,
            height=3, aspect=1.5, order=df['animals'].value_counts().index)

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM