Reputation: 3396
How can I rotate the x-axis tick labels in a Seaborn scatterplot that is plotted using subplots?
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import gridspec
import seaborn as sns
sns.set_context("talk", font_scale=1.4)
df = pd.DataFrame({'id': ['aaaaaaa','bbbbbb1','bbbbbb2','ccccc','dddddd','eeeee'],
'y': [7,2,5,8,3,7],
'cat': ['X','Y','Y','X','Z','X']
})
display(df)
fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(8,4),
gridspec_kw=dict(width_ratios=[2, 1]),
)
g1 = sns.scatterplot(data=df,
x='id', y='y', hue='cat',
s=200, ax=ax1, legend=False,
)
g2 = sns.histplot(data=df, y='y',
hue='cat', ax=ax2, binwidth=2,
multiple='stack', legend=False,
)
I have tried the following without any success:
g1.xticks(rotation = 90)
and ax1.xticks(rotation = 90)
both return AttributeError: 'AxesSubplot' object has no attribute 'xticks'
g1.set_xticklabels(g1.get_xticklabels(), rotation = 90)
based on the question here, but this removes all the tick labelsUpvotes: 1
Views: 1838
Reputation: 3396
For some reason it looks like the labels are lost in the Seaborn-Matplotlib ether.
labels = [item.get_text() for item in g1.get_xticklabels()]
print(labels)
returns a list of blanks: ['', '', '', '', '', '']
So I must remake the labels: g1.set_xticklabels(df['id'].tolist(), rotation = 90)
And confirming it works:
labels2 = [item.get_text() for item in g1.get_xticklabels()]
print(labels2)
>>['aaaaaaa', 'bbbbbb1', 'bbbbbb2', 'ccccc', 'dddddd', 'eeeee']
Upvotes: 1