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

如何用Python绘制展示categorical变量各标签观测数量的Bar Chart

分类变量计数柱状图实现方法

这里提供几种Python下快速实现你需求的方案:

方案1:Pandas 一键绘图

利用Pandas自带的绘图工具,结合value_counts()统计次数后直接生成柱状图:

import pandas as pd
import matplotlib.pyplot as plt

# 构造你提供的示例数据
df = pd.DataFrame({'COLOR': ['green', 'red', 'green', 'yellow', 'pink', 'red', 'blue']})

# 生成并展示柱状图
df['COLOR'].value_counts().plot(kind='bar', title='颜色观测数量')
plt.xlabel('颜色')
plt.ylabel('观测次数')
plt.show()

方案2:Matplotlib 手动绘制

先统计各分类的计数,再用Matplotlib绘制柱状图,自由度更高:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'COLOR': ['green', 'red', 'green', 'yellow', 'pink', 'red', 'blue']})

# 统计每个颜色的出现次数
counts = df['COLOR'].value_counts()

# 绘制柱状图
plt.bar(counts.index, counts.values)
plt.title('颜色观测数量')
plt.xlabel('颜色')
plt.ylabel('观测次数')
plt.show()

方案3:Seaborn 简化实现

Seaborn的countplot专门用于绘制分类变量的计数图,代码更简洁:

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

df = pd.DataFrame({'COLOR': ['green', 'red', 'green', 'yellow', 'pink', 'red', 'blue']})

# 直接生成计数柱状图
sns.countplot(x='COLOR', data=df)
plt.title('颜色观测数量')
plt.xlabel('颜色')
plt.ylabel('观测次数')
plt.show()

以上三种方案都能生成你需要的柱状图,清晰展示每个颜色对应的观测次数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:05:42