如何在Python Seaborn子图中将X轴文本旋转45度?
解决Seaborn Countplot子图X轴标签重叠问题
你有三个如下的DataFrame:
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt df = pd.DataFrame(['JohnJohnJohnJohn','JuneJuneJuneJune','DanDanDanDan','JohnJohnJohnJohn','DanDanDanDan','DineDineDineDine','JuneJuneJuneJune','JohnJohnJohn'],columns =['Months']) df1 = pd.DataFrame(['John_1John_1John_1','June_1June_1June_1','Dine_1Dine_1Dine_1','John_1John_1John_1','Dine_1Dine_1Dine_1','John_1John_1John_1'],columns =['Months']) df2 = pd.DataFrame(['John_2John_2','Dine_2Dine_2','Dine_2Dine_2','John_2John_2','June_2June_2','John_2John_2'],columns =['Months'])
使用Seaborn绘制子图时X轴标签出现重叠,你尝试的代码无效,核心问题是**axes是子图轴对象的数组,不能直接对整个数组调用set_xticklabels方法**,需要针对每个子图的轴单独设置。
修正方案1:逐个处理子图轴
直接对每个axes[i]单独设置X轴标签的旋转角度:
f, axes = plt.subplots(1, 3, figsize=(15, 6)) # 放大画布优化显示 # 第一个子图 sns.countplot(x='Months', data=df, order=df.Months.value_counts().index, ax=axes[0]) axes[0].set_title('1D') axes[0].set_xticklabels(axes[0].get_xticklabels(), rotation=45, ha='right') # 第二个子图 sns.countplot(x='Months', data=df1, order=df1.Months.value_counts().index, ax=axes[1]) axes[1].set_title('2D') axes[1].set_xticklabels(axes[1].get_xticklabels(), rotation=45, ha='right') # 第三个子图 sns.countplot(x='Months', data=df2, order=df2.Months.value_counts().index, ax=axes[2]) axes[2].set_title('3D') axes[2].set_xticklabels(axes[2].get_xticklabels(), rotation=45, ha='right') plt.tight_layout() # 自动调整子图间距,避免元素重叠 plt.show()
修正方案2:遍历子图轴统一设置
如果子图数量较多,用循环遍历更高效:
f, axes = plt.subplots(1, 3, figsize=(15, 6)) data_frames = [df, df1, df2] titles = ['1D', '2D', '3D'] for ax, data, title in zip(axes, data_frames, titles): sns.countplot(x='Months', data=data, order=data.Months.value_counts().index, ax=ax) ax.set_title(title) ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right') plt.tight_layout() plt.show()
关键细节说明
ha='right':设置标签右对齐,旋转后更贴合X轴刻度,避免偏移。plt.tight_layout():自动调整子图的间距和边界,确保所有标签、标题完整显示。figsize参数:适当放大画布,给长标签留出足够显示空间。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

