如何用Seaborn countplot结合分类筛选统计各TAG的NGT数量
实现代码
前置依赖导入
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt
数据读取/构造
将下面的示例数据构造逻辑替换为你自己的文件读取逻辑即可,比如df = pd.read_csv("你的数据集文件路径")
# 示例数据构造 df = pd.DataFrame({ 'ID': [1,2,3,4], 'TAG': ['A', 'B', 'C', 'A'], 'TYPE': ['GT', 'NGT', 'XT', 'NGT'] })
数据统计(无需手动筛选)
仅统计存在NGT记录的TAG
# 筛选NGT类型数据后按TAG分组计数 ngt_count = df[df['TYPE'] == 'NGT'].groupby('TAG', as_index=False)['ID'].count().rename(columns={'ID': 'NGT记录数'})
需展示所有TAG(无NGT记录的显示为0)
# 全量统计每个TAG的各TYPE数量,缺失值补0 count_full = df.groupby(['TAG', 'TYPE'], as_index=False)['ID'].count()\ .pivot(index='TAG', columns='TYPE', values='ID')\ .fillna(0).reset_index() ngt_count = count_full[['TAG', 'NGT']].rename(columns={'NGT': 'NGT记录数'})
绘图实现
方案1:seaborn 可视化
sns.set_style("whitegrid") ax = sns.barplot(data=ngt_count, x='TAG', y='NGT记录数', palette='viridis') # 柱上添加数值标签 for p in ax.patches: height = p.get_height() ax.text(p.get_x() + p.get_width()/2, height, f'{int(height)}', ha='center', va='bottom') plt.title('各TAG对应NGT类型记录数') plt.tight_layout() plt.show()
方案2:matplotlib 原生可视化
plt.figure(figsize=(6, 4)) plt.bar(ngt_count['TAG'], ngt_count['NGT记录数'], color='#2ecc71', alpha=0.7) # 柱上添加数值标签 for tag, cnt in zip(ngt_count['TAG'], ngt_count['NGT记录数']): plt.text(tag, cnt, str(int(cnt)), ha='center', va='bottom') plt.xlabel('TAG') plt.ylabel('NGT记录数') plt.title('各TAG对应NGT类型记录数') plt.grid(axis='y', linestyle='--', alpha=0.6) plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者sinha-shaurya
相关产品推荐
相关产品推荐

