python - 通过升序或降序订购 python Seaborn barplot
问题描述
这是我当前的代码,使用美国境内的死因数据集(按发生次数):
`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)`
虽然这段代码没有给我任何错误,但它似乎所做的只是以不同的随机顺序重新排列条形图,如下所示:
为什么会这样?我做错了什么,是否有某种方法可以将条形重新排列为我不知道的升序或降序?
解决方案
您必须传递 to 的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:])
推荐阅读
- string - 在字符串中查找字符串的所有实例
- git - 如何注释文件中的每个更改,以便它们对 git 可见但隐藏在实际文件中
- python-3.x - 错误:环境 /Users/myuser/.virtualenvs/iron 不包含激活脚本
- flutter-moor - 如何通过一对多连接创建 Flutter Moor 关系
- scala - scala.io.StdIn.readLine() 是阻塞调用吗?
- vue.js - vuejs - 用于不同 url 的缓存数据
- javascript - 删除与某个子值关联的整个记录
- c - 如何初始化内存并将其分配给数据结构并传递给另一个函数
- php - Symfony cmd 错误“目标实体..无法在..中找到”
- c# - 如何在 Blazor 中实现路由器动画?