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

如何用Pandas创建简单的是/否countplot?解决轴显示异常问题

解决Seaborn Countplot显示错误的问题

你的问题出在对countplot的用法理解上:countplot是用来统计原始数据集中每个类别出现的频数,但你的DataFrame里已经是汇总好的计数结果(1561和635),并非单条样本的原始数据。所以countplot会把Smoking列的两个数值当作独立类别,每个类别仅出现1次,最终导致y轴范围被限制在0-1,x轴显示的是这两个计数数值,完全不符合你的需求。

解决方案:改用Barplot

seaborn.barplot支持直接使用已汇总的数据,只需指定类别和对应的计数值即可。

方式1:保留索引作为x轴类别

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

# 构建数据
data_dict = {"Condition": ['no','yes'], "Smoking":[1561,635]}
frame = pd.DataFrame(data=data_dict)
frame.set_index("Condition", inplace=True)

# 绘图设置
plt.figure(figsize=(8,6))
sns.set_palette("pastel", 8)

# 使用barplot,x取索引(Condition的no/yes),y取Smoking的计数值
sns.barplot(x=frame.index, y=frame["Smoking"])

# 自定义标签和标题
plt.xlabel("Condition")
plt.ylabel("Count")
plt.title("Smoking Count by Condition")

plt.show()

方式2:重置索引,用列作为x轴类别

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

# 构建数据
data_dict = {"Condition": ['no','yes'], "Smoking":[1561,635]}
frame = pd.DataFrame(data=data_dict)
# 若之前设置了索引,可重置让Condition回到列
# frame.set_index("Condition", inplace=True)
# frame = frame.reset_index()

# 绘图设置
plt.figure(figsize=(8,6))
sns.set_palette("pastel", 8)

# 直接指定x为Condition列,y为Smoking列
sns.barplot(data=frame, x="Condition", y="Smoking")

# 自定义标签和标题
plt.ylabel("Count")
plt.title("Smoking Count by Condition")

plt.show()

关键说明

  • countplot适合处理原始样本数据(比如每条记录对应一个样本,标记为yes/no),自动统计每个类别出现的次数。
  • barplot适合处理已汇总的数据,直接传入类别和对应的数值即可生成符合需求的柱状图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 02:50:09