Ordering a python Seaborn bar-plot by ascending or descending?

血红的双手。 提交于 2019-12-25 01:49:01

问题


This is my current code using a dataset of causes of death within the united states by number of occurrences:

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

This results in a chart that looks like this:

I was attempting to re-order the graph such that the bars were in descending order. I added a bit to my code and got this:

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

While this code did not give me any errors, all it seemed to do was reorder the bars in a different, random order like so:

Why does this happen? What am I doing wrong, and is there some way of rearranging the bars into ascending or descending order that I am not aware of?


回答1:


You have to pass values of x= to order=. In your case, I would do:

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)

Or, if you want to remove the "All causes" bar:

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




回答2:


You can set the order argument of sns.catplot() to your preferred order. You can use df['col'].value_counts().index to get this order. You haven't provided an example of your data, so allow me to provide an easily reproducible example.

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)



来源:https://stackoverflow.com/questions/59241052/ordering-a-python-seaborn-bar-plot-by-ascending-or-descending

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!