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

如何为Seaborn计数图的target变量设置自定义标签(0=无心脏病,1=有心脏病)

解决方法

有两种简单方式可以实现目标变量标签的替换:

方法一:直接修改坐标轴刻度标签

在你现有代码基础上,通过ax.set_xticklabels()方法直接替换x轴刻度文本,代码如下:

import seaborn as sns
import matplotlib.pyplot as plt

ax = sns.countplot(x='target', hue='sex', data=heartt)
# 按顺序设置x轴刻度标签,对应target的0和1
ax.set_xticklabels(['无心脏病', '有心脏病'])
plt.show()

方法二:提前替换数据集中的target值

先将数据里target列的数值替换为对应文本,再直接绘图,无需额外修改刻度:

import seaborn as sns
import matplotlib.pyplot as plt

# 复制原数据避免修改原始数据,替换target值
heartt_modified = heartt.copy()
heartt_modified['target'] = heartt_modified['target'].map({0: '无心脏病', 1: '有心脏病'})

ax = sns.countplot(x='target', hue='sex', data=heartt_modified)
plt.show()

两种方法都能实现你需要的标签效果,可根据使用习惯选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:05:25