如何使用子图在 Seaborn 散点图中旋转 x 轴刻度标签

How to rotate x-axis tick lables in Seaborn scatterplot using subplots

如何在使用子图绘制的 Seaborn 散点图中旋转 x 轴刻度标签?

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,
                 )

我尝试了以下方法但没有成功:

  1. g1.xticks(rotation = 90)ax1.xticks(rotation = 90) 都 return
    AttributeError: 'AxesSubplot' object has no attribute 'xticks'
  2. g1.set_xticklabels(g1.get_xticklabels(), rotation = 90) 基于问题 ,但这会删除所有刻度标签

出于某种原因,标签似乎在 Seaborn-Matplotlib 以太中丢失了。

labels = [item.get_text() for item in g1.get_xticklabels()]
print(labels)

returns 空白列表:['', '', '', '', '', '']

所以我必须重新制作标签:g1.set_xticklabels(df['id'].tolist(), rotation = 90)

并确认它有效:

labels2 = [item.get_text() for item in g1.get_xticklabels()]
print(labels2)
>>['aaaaaaa', 'bbbbbb1', 'bbbbbb2', 'ccccc', 'dddddd', 'eeeee']