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

如何使用Python绘制柱状图统计数据集各出现频次的元素数量

Python实现Tracking ID频次分布柱状图

实现逻辑

核心是做两层计数匹配xy轴映射关系:

  • 第一层:统计每个唯一tracking_id在数据集中的出现总次数
  • 第二层:统计「出现1次的ID有多少个、出现2次的ID有多少个……出现10次的ID有多少个」,作为y轴数值
  • 最后固定x轴刻度为1-10,绘制柱状图即可

完整代码

先安装所需依赖:
pip install pandas matplotlib

可直接运行的实现代码:

import pandas as pd
import matplotlib.pyplot as plt

# ---------------------- 数据统计部分 ----------------------
# 将下方df替换为你自己的DataFrame变量名
# df = 你的本地数据集

# 第一步:统计每个tracking_id的出现次数
id_occur_times = df['tracking_id'].value_counts()

# 第二步:统计每个出现次数对应的ID总数量,按x轴1-10补全缺失值
freq_count = id_occur_times.value_counts().sort_index()
x_ticks = range(1, 11)
# 过滤1-10范围外的次数,对没有对应ID的次数(比如无ID出现3次)补0,避免柱子断档
freq_count = freq_count.reindex(x_ticks, fill_value=0)

# ---------------------- 绘图部分 ----------------------
plt.figure(figsize=(9, 5), dpi=100)
bars = plt.bar(freq_count.index, freq_count.values, width=0.7, color='#2E86AB')

# 配置坐标轴和标题
plt.xlabel('Tracking ID出现次数', fontsize=11)
plt.ylabel('对应次数下的Tracking ID数量', fontsize=11)
plt.title('Tracking ID频次分布柱状图', fontsize=13, pad=15)
plt.xticks(x_ticks)
plt.grid(axis='y', linestyle='--', alpha=0.4)

# 可选:在柱子顶部标注具体数值
for bar in bars:
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2., height + 0.2,
             f'{int(height)}',
             ha='center', va='bottom', fontsize=9)

plt.tight_layout()
plt.show()

提示:如果你的tracking_id列存在空值,统计前先执行df = df.dropna(subset=['tracking_id'])清洗空数据,避免统计结果偏差。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 11:15:29