Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seaborn Boxplot: get the xtick labels

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.

like image 979
Raja Sattiraju Avatar asked Mar 15 '17 15:03

Raja Sattiraju


2 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()])
like image 109
ImportanceOfBeingErnest Avatar answered Sep 18 '22 22:09

ImportanceOfBeingErnest


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()
like image 39
Kairat Sharshenbaev Avatar answered Sep 18 '22 22:09

Kairat Sharshenbaev