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

如何解决countplot绘图x轴标签重叠问题并对Age字段按区间分组

解决方法

可以通过先对Age字段做自定义等距分箱,再传入countplot绘图的方式实现需求,具体操作如下:

  • 第一步:生成自定义格式的年龄分组字段
    使用pandas的cut()方法完成年龄分箱,直接生成你需要的23-33、33-43格式的标签:
import pandas as pd
# 定义分箱边界,步长为10,覆盖23到85的全年龄范围
bins = range(23, 96, 10)
# 生成区间标签
labels = [f'{i}-{i+10}' for i in bins[:-1]]
# 新增年龄分组字段到原数据框
df['Age_Group'] = pd.cut(
    df['Age'],
    bins=bins,
    labels=labels,
    right=False,
    include_lowest=True
)

参数说明:

  • right=False:设置区间为左闭右开规则,避免年龄刚好为区间边界值时的归类歧义

  • include_lowest=True:确保最小值23会被正确归入第一个区间

  • 第二步:修改countplot绘图逻辑
    将原代码中年龄计数图的x轴参数替换为新生成的Age_Group字段即可,若仍有标签重叠可打开x轴标签旋转的配置:

import seaborn as sns
import matplotlib.pyplot as plt

fig, axes = plt.subplots(2,2,figsize=(11,11))

# 替换x字段为分箱后的年龄组
sns.countplot(ax=axes[0,0],x='Age_Group',hue='Credit_Product',data=df)
# 若标签仍有重叠可启用下方代码调整旋转角度
axes[0,0].set_xticklabels(axes[0,0].get_xticklabels(), rotation=40, ha="right")

sns.countplot(ax=axes[0,1],x='Gender',hue='Credit_Product',data=df)
sns.countplot(ax=axes[1,0],x='Region_Code',hue='Credit_Product',data=df)
sns.countplot(ax=axes[1,1],x='Occupation',hue='Credit_Product',data=df)

plt.subplots_adjust(left=0.1, right=1.1)
plt.tight_layout()
plt.legend(bbox_to_anchor=(1.1, 1.05))
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:48:03