50

I have a question that is basically the same as a question back from 2014 (see here). However, my script still throws an error.

Here is what I do: I have a pandas dataframe with a few columns. I plot a simple boxplot comparison.

g = sns.boxplot(x='categories', y='oxygen', hue='target', data=df)
g.set_xticklabels(rotation=30)

The graph looks like this:

enter image description here

I'd like to rotate the x-labels by 30 degrees. Hence I use g.set_xticklabels(rotation=30). However, I get the following error:

set_xticklabels() missing 1 required positional argument: 'labels'

I don't know how to pass the matplotlib labels argument to seaborns sns.boxplot. Any ideas?

Rachel
  • 1,937
  • 7
  • 31
  • 58

2 Answers2

87

The question you link to uses a factorplot. A factorplot returns its own class which has a method called set_xticklabels(rotation). This is different from the set_xticklabels method of the matplotlib Axes.

In the linked question's answers there are also other options which you may use

ax = sns.boxplot(x='categories', y='oxygen', hue='target', data=df)
ax.set_xticklabels(ax.get_xticklabels(),rotation=30)

or

ax = sns.boxplot(x='categories', y='oxygen', hue='target', data=df)
plt.setp(ax.get_xticklabels(), rotation=45)
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • 1
    Thanks, Do you have any idea why `myplot.set_xticklabels(myplot.get_xticklabels(), rotation=45)` not working but `plt.setp(myplot.get_xticklabels(), rotation=45)` works? – Medhat Mar 22 '19 at 17:50
  • 4
    Maybe I was not clear. The second answer works when I use it, the first makes the labels disappear. – Medhat Mar 24 '19 at 02:05
  • 1
    Both solutions work when I use them. I suppose the problem you're having is outside of the two lines shown here. – ImportanceOfBeingErnest Mar 24 '19 at 02:42
  • 2
    Hi, great tip @ImportanceOfBeingErnest, many thanks! Do you know why I keep getting a big text below the graph? My boxplot is ok, the output has no problem at all, however, I got several lines why the labels, for example [Text(0, 0, '1984'), Text(0, 0, '1985'), – dekio Apr 24 '19 at 17:46
  • 3
    @dekio put ; at the end of the line – Noa Yehezkel Mar 05 '20 at 19:13
5

If you do not need to reset labels: ax.tick_params(axis='x', labelrotation=90)

Dmitry
  • 71
  • 2
  • 2