Seaborn PairPlot rotate x tick labels. Categorical data labels are overlapping

Question:

I’m trying to create plots which show the correlation of the “value” parameter to different categorical parameters. Here’s what I have so far:

plot = sns.pairplot(df, x_vars=['country', 'tier_code', 'industry', 'company_size', 'region'], y_vars=['value'], height=10)

Which produces the following set of plots:

enter image description here

As you can see, the x axis is extremely crowded for the “country” and “industry” plots. I would like to rotate the category labels 90 degrees so that they wouldn’t overlap.

All the examples for rotating I could find were for other kinds of plots and didn’t work for the pairplot. I could probably get it to work if I made each plot separately using catplot, but I would like to make them all at once. Is that possible?

I am using Google Colab in case it makes any difference. My seaborn version number is 0.10.0.

Asked By: user3207874

||

Answers:

You can rotate x-axis labels as:

plot = sns.pairplot(df, x_vars=['country', 'tier_code', 'industry', 'company_size', 'region'], 
                     y_vars=['value'], height=10)

rotation = 90
for axis in plot.fig.axes:   # get all the axis
     axis.set_xticklabels(axis.get_xticklabels(), rotation = rotation)

plot.fig.show()

Hope it helps.

Answered By: Manish KC

Manish’s answer uses the get_xticklabels method, which doesn’t always play well with the higher level seaborn functions in my experience. So here’s a solution avoiding that. Since I don’t have your data, I’m using seaborn’s tips dataset for an example.

I’m naming the object returned by sns.pairplot() grid, just to remind us that it is a PairGrid instance. In general, its axes attribute yields a two-dimensional array of axes objects, corresponding to the subplot grid. So I’m using the flat method to turn this into a one-dimensional array, although it wouldn’t be necessary in your special case with only one row of subplots.

In my example I don’t want to rotate the labels for the third subplot, as they are single digits, so I slice the axes array accordingly with [:2].

import seaborn as sns
sns.set()

tips = sns.load_dataset("tips")

grid = sns.pairplot(tips, x_vars=['sex', 'day', 'size'], y_vars=['tip']) 

for ax in grid.axes.flat[:2]:
    ax.tick_params(axis='x', labelrotation=90)

sample plot with rotated x labels

Answered By: Arne