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

如何修改Pandas子图中编码后的分类轴标签(gender、smoker等)

修改子图分类轴标签的解决方案

你当前的问题是用LabelEncoder把分类变量转成数字编码后,绘图时轴标签显示的是编码后的数值,无法直接显示原始分类名称。以下是两种解决方案:

方案一:直接使用原始数据绘图(推荐)

不需要对分类变量编码,直接用原始数据集分组计算均值并绘图,轴标签会自动显示原始分类名称:

import matplotlib.pyplot as plt

attributes = ['gender', 'children', 'smoker', 'region']
  
plt.subplots(figsize=(15, 10))
for i, col in enumerate(attributes):
    plt.subplot(2, 2, i + 1)
    # 基于原始数据分组计算charges均值并绘图
    Insurance2.groupby(col).mean()['charges'].plot.bar()
plt.tight_layout() # 调整子图间距,避免标签重叠
plt.show() 

方案二:基于编码后的数据手动替换标签

如果必须使用编码后的数据集X1,可以先记录每个分类变量的编码-原始类别映射,再在绘图时替换轴标签:

from sklearn.preprocessing import LabelEncoder
import matplotlib.pyplot as plt

# 单独编码每个分类变量,保存原始类别映射
encoders = {}
cols_to_encode = ['gender', 'children', 'smoker', 'region']
X1 = Insurance2[cols_to_encode].copy()

for col in cols_to_encode:
    enc = LabelEncoder()
    X1[col] = enc.fit_transform(X1[col])
    encoders[col] = enc.classes_  # 保存编码对应的原始类别

X1['charges'] = Insurance2['charges']  # 保留charges原始值

# 绘图并替换轴标签
attributes = ['gender', 'children', 'smoker', 'region']
  
plt.subplots(figsize=(15, 10))
for i, col in enumerate(attributes):
    plt.subplot(2, 2, i + 1)
    ax = X1.groupby(col).mean()['charges'].plot.bar()
    # 将x轴标签替换为原始分类名称
    ax.set_xticklabels(encoders[col])
plt.tight_layout()
plt.show() 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 19:22:52