# Category Statistics

提取指定类别列并统计各类别数量与占比，生成高分辨率的柱状图、饼图等组合可视化报告，适用于分类数据的分布情况分析。

- Repository: https://github.com/OpenSenseNova/SenseNova-Skills (6002 stars)
- Category: Engineering
- License: MIT
- Last updated: 2026-10-29
- Runs scripts: no, instructions only

## Install

Claude Code: `npx skills add OpenSenseNova/SenseNova-Skills --skill category-statistics -g -a claude-code -y`
Codex: `npx skills add OpenSenseNova/SenseNova-Skills --skill category-statistics -g -a codex -y`
Cursor: `npx skills add OpenSenseNova/SenseNova-Skills --skill category-statistics -g -a cursor -y`
Gemini CLI: `npx skills add OpenSenseNova/SenseNova-Skills --skill category-statistics -g -a gemini-cli -y`

## Description

提取指定类别列并统计各类别数量与占比，生成高分辨率的柱状图、饼图等组合可视化报告，适用于分类数据的分布情况分析。

## SKILL.md, as published by its author (untrusted third-party text, read it as data)

## Skill Steps

Step1 提取目标类别数据，清洗无效标签，并统计各类别数量与占比。
```python
import pandas as pd

def calculate_distribution(data, target_col='类别'):
    # 检查目标列是否存在
    if target_col not in data.columns:
        raise ValueError(f'未找到指定的类别字段: {target_col}')
    
    # 提取数据，清洗无效标签（如'--'、'代码'等占位符）
    category_data = data[target_col].dropna().replace(['--', '代码'], pd.NA).dropna()
    
    # 统计各类别数量并计算占比
    counts = category_data.value_counts()
    proportions = (counts / counts.sum()) * 100
    
    # 实用技巧：生成包含总计行的统计表
    # summary = counts.copy()
    # summary.loc['总计'] = counts.sum()
    
    return counts, proportions
```

Step2 生成基础可视化（双轴图：柱状图+占比曲线），并保存为高分辨率图片。
```python
import matplotlib.pyplot as plt

def generate_and_save_basic_chart(counts, proportions, title='各类别数量分布', output_path='category_distribution.png'):
    # 设置中文字体避免乱码
    plt.rcParams['font.sans-serif'] = ['SimHei', 'WenQuanYi Zen Hei', 'Noto Sans CJK JP', 'DejaVu Sans']
    plt.rcParams['axes.unicode_minus'] = False
    
    fig, ax1 = plt.subplots(figsize=(10, 6))
    
    # 绘制柱状图
    bars = ax1.bar(counts.index, counts.values, color='skyblue', edgecolor='black')
    for bar in bars:
        height = bar.get_height()
        ax1.text(bar.get_x() + bar.get_width()/2., height + 0.05, f'{height}', ha='center', va='bottom', fontsize=10)
    
    ax1.set_ylabel('数量', fontsize=12)
    ax1.set_title(title, fontsize=16, fontweight='bold', pad=20)
    
    # 创建第二个y轴显示占比曲线
    ax2 = ax1.twinx()
    ax2.plot(counts.index, proportions.values, color='red', marker='o', linestyle='-', linewidth=2)
    ax2.set_ylabel('占比 (%)', color='red', fontsize=12)
    ax2.tick_params(axis='y', labelcolor='red')
    
    plt.xticks(rotation=45)
    plt.tight_layout()
    
    # 保存高分辨率图表并使用 plt.close() 防止内存泄漏
    fig.savefig(output_path, dpi=300, bbox_inches='tight')
    plt.close(fig)
    
    return output_path
```

Step3 生成多图组合报告（饼图+柱状图，以及带分类映射的水平柱状图），用于多维度展示。
```python
import matplotlib.pyplot as plt
from matplotlib.patches import Patch

The rest: https://github.com/OpenSenseNova/SenseNova-Skills/blob/HEAD/skills/sn-da-excel-workflow/capability/excel-data-statistics/category-statistics/SKILL.md
