Seaborn Boxplot: get the xtick labels

Question:

I am using Seaborn to make a boxplot using data from a pandas dataframe.

colorpalette = sns.hls_palette(8,h=.9)
g = sns.boxplot(x="estimator", y="mean_score", data=dFrame, palette=colorpalette)

g.set(ylabel='Mean Accuracy', xlabel='')
plt.show()

enter image description here

This results me in the previous figure. As you can see the ticklabels are too long to be in one line. So, I plan to use textwrap on the xticklabels to span them over multiple rows. In order to get the labels, I tried using

g.xaxis.get_ticklabels()

Returns me the following

<a list of 9 Text major ticklabel objects>

If I try it in a loop like this

for item in g.xaxis.get_ticklabels():
    print(item)

I get the following output

Text(0,0,'ExtraTreesClassifier')
Text(1,0,'RandomForestClassifier')
Text(2,0,'GradientBoostingClassifier')
Text(3,0,'LogisticRegression')
Text(4,0,'DecisionTreeClassifier')
Text(5,0,'kNearestNeighbors')
Text(6,0,'LinearSVC')
Text(7,0,'Perceptron')

Is there a way to do it more efficiently using default functions/methods in seaborn.

Asked By: Raja Sattiraju

||

Answers:

Having a matplotlib axes instance ax (as it is e.g. returned by seaborn plots),

ax = sns.boxplot(...)

allows to obtain the ticklabels as

ax.get_xticklabels()

The easiest way to get the texts out of the list would be

texts = [t.get_text()  for t in ax.get_xticklabels()]

Wrapping the text could be done as well on the fly

texts = [textwrap.fill(t.get_text(), 10)  for t in ax.get_xticklabels()]

and even setting the text back as ticklabels can be done in the same line

ax.set_xticklabels([textwrap.fill(t.get_text(), 10)  for t in ax.get_xticklabels()])

The accepted answer didn’t work for me (there was message like: ‘FacetGrid’ object has no attribute ‘get_xticklabels’.

but this worked:

g.fig.autofmt_xdate()
Answered By: Kairat Sharshenbaev

Instead of warping the text
You can rotate the labels, and add a margin at the bottom

plt.xticks(rotation=60, ha='right')
plt.subplots_adjust(bottom=0.3)
Answered By: lahmania
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.