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

如何解决seaborn绘制2×2条形子图时y轴特征标签遮挡问题

问题原因

右列子图的y轴刻度标签默认绘制在子图左侧,刚好处于两列子图的中间缝隙位置,类似Antihypertensive_medication_value的长文本长度超过默认缝隙宽度时,就会延伸到左列子图区域造成遮挡,同时matplotlib默认布局没有为长标签预留足够显示空间。

推荐方案(符合可视化规范)

你的左右两列同组子图y轴特征类别完全一致,右列重复显示y轴标签属于冗余信息,直接隐藏右列y轴刻度标签即可彻底解决遮挡,同时让图面更简洁,修正后完整代码如下:

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

fig, axes = plt.subplots(2, 2, figsize=(10, 8), sharex=True)

df_A_1 = pd.DataFrame({'Features': ['age', 'weight', 'height', 'waist'],
                              'imp': [0.15, 0.1, 0.07, 0.05]
                              })
df_A_2 = pd.DataFrame({'Features': ['age', 'weight', 'height', 'waist'],
                              'imp': [0.17, 0.12, 0.08, 0.07]
                              })
df_B_1 = pd.DataFrame({'Features': ['Antihypertensive_medication_value', 'KDOSE', 'K', 'ARR_1', 'TG'],
                              'imp': [0.135, 0.107, 0.094, 0.059, 0.079]
                              })
df_B_2 = pd.DataFrame({'Features': ['Antihypertensive_medication_value', 'KDOSE', 'K', 'ARR_1', 'TG'],
                              'imp': [0.15, 0.13, 0.07, 0.06, 0.04]
                              })

# 显式指定x/y参数,兼容所有版本seaborn
sns.barplot(x='imp', y='Features', data=df_A_1, ax=axes[0, 0], color='lightgrey')
sns.barplot(x='imp', y='Features', data=df_A_2, ax=axes[0, 1], color='black')
sns.barplot(x='imp', y='Features', data=df_B_1, ax=axes[1, 0], color='lightgrey')
sns.barplot(x='imp', y='Features', data=df_B_2, ax=axes[1, 1], color='black')

# 隐藏右列子图的冗余y轴刻度标签
axes[0,1].set_yticklabels([])
axes[1,1].set_yticklabels([])

# 自动调整布局,避免标签被画布边缘截断
plt.tight_layout()
plt.show()
可选方案

如果需要保留右列的y轴标签,可选择以下任意一种方式:

  • 右列y轴刻度右移:将右列两个子图的y轴刻度和标签调整到子图右侧显示,不占用两列中间空间,在绘图代码后追加如下内容:
for ax in [axes[0,1], axes[1,1]]:
    ax.yaxis.tick_right()
plt.tight_layout()
  • 手动调整间距:通过subplots_adjust增大列间距、预留侧边空间适配长标签,在绘图代码后追加如下内容:
# wspace为列间距比例,right为画布右侧边界位置,可根据标签长度调整数值
plt.subplots_adjust(wspace=0.4, right=0.85)

注意:手动设置subplots_adjust后不要调用tight_layout(),否则手动设置的间距会被自动布局覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 03:39:27