Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change the order of factor plot in seaborn

My data looks like this:

m=pd.DataFrame({'model':['1','1','2','2','13','13'],'rate':randn(6)},index=['0', '0','1','1','2','2'])

I want to have the x-axis of factor plot ordered in [1,2,13] but the default is [1,13,2].

Does anyone know how to change it?

Update: I think I have figured it out in the following way, but maybe there is a better way by using an index to do that?

sns.factorplot('model','rate',data=m,kind="bar",x_order=['1','2','13'])
like image 590
MYjx Avatar asked Jul 07 '14 20:07

MYjx


People also ask

How do I change my legend order in seaborn?

To change the position of a legend in a seaborn plot, you can use the plt. legend() command. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.

How do you order boxplot in seaborn?

Seaborn's boxplot() function easily allows us to choose the order of boxplots using the argument “order”. The argument order takes a list ordered in the way we want. Here we manually specify the order of boxes using order as order=[“Professional”,”Less than bachelor's”,”Bachelor's”,”Master's”, 'PhD'].

What is Factorplot in seaborn?

Factor Plot is used to draw a different types of categorical plot . The default plot that is shown is a point plot, but we can plot other seaborn categorical plots by using of kind parameter, like box plots, violin plots, bar plots, or strip plots.


2 Answers

Your update to the post shows the correct way to do it, i.e. you should pass a list of x values to order in the order you want them plotted. The default for numeric data is to plot in sorted order, so if you have numeric values it's best to keep them as integers or floats instead of strings, so they will be in "natural" order.

like image 98
mwaskom Avatar answered Sep 18 '22 22:09

mwaskom


As @Pablo wrote in his comment and @Archie correctly mentioned in their answer:

x_order should be replaced by order

For those who came here looking for a sort solution for kind="count", it is possible to do so:

sns.catplot(x="model", data=m, kind="count", order=m.model.value_counts().index)

It's because by default value_counts method will return descending sorted values by count.

like image 36
Rafe Avatar answered Sep 17 '22 22:09

Rafe