Rotate xtick labels in seaborn boxplot?

Rachel picture Rachel · Jul 6, 2017 · Viewed 35.2k times · Source

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?

Answer

ImportanceOfBeingErnest picture ImportanceOfBeingErnest · Jul 6, 2017

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)