You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在使用sns.boxplot时将子图222的X轴标签旋转90°

如何旋转Seaborn多子图布局中指定子图的X轴标签

你之前的尝试失效核心原因是没有绑定目标子图的Axes对象,且使用set_xticklabels时未传入正确的标签内容。以下是可行的解决方案:

完整修改代码

import matplotlib.pyplot as plt
import seaborn as sns

fig = plt.figure(figsize=(12, 8))

# 子图1
ax1 = fig.add_subplot(221)
sns.boxplot(x='MSZoning', y='SalePrice', data=df_train, ax=ax1)

# 子图2(目标子图,位置222)
ax2 = fig.add_subplot(222)
sns.boxplot(x='Neighborhood', y='SalePrice', data=df_train, ax=ax2)
# 旋转X轴标签90度
ax2.tick_params(axis='x', labelrotation=90)

# 子图3
ax3 = fig.add_subplot(223)
sns.boxplot(x='OverallCond', y='SalePrice', data=df_train, ax=ax3)

# 子图4
ax4 = fig.add_subplot(224)
sns.boxplot(x='OverallQual', y='SalePrice', data=df_train, ax=ax4)

plt.tight_layout()  # 自动调整布局,避免标签与其他子图重叠
plt.show()

关键说明

  1. 获取Axes对象:给每个子图赋值ax变量(如ax2 = fig.add_subplot(222)),确保后续操作能精准定位到目标子图。
  2. 两种有效旋转方式:
    • 方法一(推荐):用tick_params直接指定轴和旋转角度,无需额外获取标签:
      ax2.tick_params(axis='x', labelrotation=90)
      
    • 方法二:如果需要自定义标签内容,先获取原标签再设置旋转:
      ax2.set_xticklabels(ax2.get_xticklabels(), rotation=90)
      
      你之前的代码中未传入labels参数,导致标签丢失,这也是失效的原因之一。
  3. 布局优化:添加plt.tight_layout()可以自动调整子图间距,防止旋转后的X轴标签与相邻子图重叠。

内容的提问来源于stack exchange,提问作者Lucas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 10:07:42