Rotate xtick labels in seaborn boxplot?

53,735

Solution 1

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)

Solution 2

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

Share:
53,735
Rachel
Author by

Rachel

Ph.D.in Economics with a background in natural sciences, very much interested in Python and Stata. Especially interested in graphic illustration. More and more interested in panel data and cool estimation methods (spatial/multilevel regressions) among others.

Updated on July 09, 2022

Comments

  • Rachel
    Rachel almost 2 years

    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?

  • Medhat
    Medhat about 5 years
    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
    Medhat about 5 years
    Maybe I was not clear. The second answer works when I use it, the first makes the labels disappear.
  • ImportanceOfBeingErnest
    ImportanceOfBeingErnest about 5 years
    Both solutions work when I use them. I suppose the problem you're having is outside of the two lines shown here.
  • dekio
    dekio about 5 years
    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'),
  • Noa Yehezkel
    Noa Yehezkel about 4 years
    @dekio put ; at the end of the line