23

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'])
Archie
  • 2,247
  • 1
  • 18
  • 35
MYjx
  • 4,157
  • 9
  • 38
  • 53
  • I'm unable to replicate on OS X with Python 2.7.6, I get the order that you want. – Ffisegydd Jul 07 '14 at 20:18
  • Use the `x_order` keyword argument. – mwaskom Jul 07 '14 at 20:25
  • @Ffisegydd, that would most likely be: `import seaborn as sb; sb.factorplot('model', 'rate', data=m)`. I got the OP intended order of `[1, 2, 13]` as well. – CT Zhu Jul 07 '14 at 20:28
  • I figured out my problem. cuz i changed the type of the model to string that is why 11 will appear earlier than 2. Thank you so much for all your help!!! :) But actually I am still curious about x_order, do I have to specify an index to do that? – MYjx Jul 07 '14 at 20:41
  • hi mwaskom thank you so much for your help! I figured it out in this way, please see the update but I am still curious the way using index to do that. Thank you! – MYjx Jul 07 '14 at 21:48

3 Answers3

25

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.

mwaskom
  • 46,693
  • 16
  • 125
  • 127
3

From the documentation it appears that the seaborn API has updated again, the argument x_order should be replaced by order:

sns.factorplot('model', 'rate', data=m, kind="bar", order=['1','2','13'])

Also, factorplot has been renamed and will be removed in future releases; it is replaced by catplot:

sns.catplot('model', 'rate', data=m, kind="bar", order=['1','2','13'])
Archie
  • 2,247
  • 1
  • 18
  • 35
  • Nope, it is `order` instead of `row_order`, `row_order` only works when you specify the `row` parameter, and it outputs each bar into its own figure – Cheng May 14 '19 at 08:01
1

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.

Rafe
  • 395
  • 1
  • 4
  • 15