본문으로 건너뛰기
cccskills
무료GitHub에 공개

stacked-chart-visualization

Turn percentage strings into numeric data, calculate the remaining share needed to reach 100%, and create stacked bar charts. Compare category composition across periods or groups and save the chart as a high-resolution image.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

원문원문 설명 보기

处理包含百分比字符串的分类占比数据,通过补全缺失维度并生成堆叠柱状图,直观展示多维度构成随时间或分类的变化趋势。

설치 방법 보기

이럴 때 유용합니다

  • Charting monthly changes in category shares
  • Comparing composition across groups
  • Calculating an Other category from remaining percentages
  • Saving composition charts as high-resolution images

포함된 파일(1)

  • SKILL.md3.5 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Stacked_Chart_Visualization

Step1 定义百分比转换函数并提取原始数据。通过正则表达式或字符串处理将百分比格式转换为可计算的浮点数。

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

# 配置中文字体,确保图表标签正常显示
plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

def convert_percentage(val):
    """
    将百分比字符串转换为浮点数。
    处理逻辑:去除百分号并转换为 float,若已经是数值则直接返回。
    """
    if isinstance(val, str):
        return float(val.strip('%'))
    return val

# 示例数据提取逻辑(实际应用中替换为从 DataFrame 提取)
time_labels = ['1月', '2月', '3月', '4月', '5月', '6月'] # 泛化时间轴
cat1_raw = ['23.21%', '22.98%', '24.31%', '24.53%', '23.84%', '24.80%']
cat2_raw = ['25.17%', '25.67%', '25.77%', '25.98%', '25.17%', '25.61%']
cat3_raw = ['28.12%', '28.37%', '26.58%', '25.83%', '26.49%', '25.17%']

cat1_ratios = [convert_percentage(x) for x in cat1_raw]
cat2_ratios = [convert_percentage(x) for x in cat2_raw]
cat3_ratios = [convert_percentage(x) for x in cat3_raw]

Step2 构建结构化数据表,将清洗后的数值整合进 DataFrame 以便进行向量化计算。

# 构建包含时间维度和各分类占比的结构化数据表
df = pd.DataFrame({
    'group_col': time_labels,
    'cat_1': cat1_ratios,
    'cat_2': cat2_ratios,
    'cat_3': cat3_ratios
})

Step3 计算缺失维度的占比。在已知部分维度占比的情况下,通过总和 100% 的约束推算剩余维度的数值,并进行数据校验。

# 计算已知维度的总占比
target_cols = ['cat_1', 'cat_2', 'cat_3']
df['current_total'] = df[target_cols].sum(axis=1)

# 推算剩余维度(如“其他”或特定分类)的占比
df['cat_remainder'] = 100 - df['current_total']

# 验证数据完整性:确保所有维度相加接近 100
df['final_check'] = df[target_cols + ['cat_remainder']].sum(axis=1)

Step4 使用堆叠柱状图进行可视化。核心在于利用 bottom 参数逐层累加高度,并优化图表美学配置。

# 设置绘图风格与画布
plt.figure(figsize=(12, 6), dpi=100)
sns.set_style('whitegrid')

# 核心堆叠逻辑:每一层的 bottom 是前几层高度的总和
plt.bar(df['group_col'], df['cat_1'], label='分类1', color='#5DADE2')
plt.bar(df['group_col'], df['cat_2'], bottom=df['cat_1'], label='分类2', color='#58D68D')
plt.bar(df['group_col'], df['cat_3'], bottom=df['cat_1'] + df['cat_2'], label='分类3', color='#EC7063')
plt.bar(df['group_col'], df['cat_remainder'], bottom=df['cat_1'] + df['cat_2'] + df['cat_3'], label='其他', color='#F4D03F')

# 图表辅助元素优化
plt.xlabel('统计周期')
plt.ylabel('占比 (%)')
plt.title('多维度占比变化趋势分析')
plt.legend(loc='upper right', bbox_to_anchor=(1.1, 1))
plt.xticks(rotation=45) # 避免标签重叠
plt.tight_layout()

Step5 导出分析结果。将生成的图表保存为高分辨率图片,并清理内存。

# 保存图表,设置 dpi 确保清晰度,bbox_inches 确保标签不被截断
output_path = 'stacked_ratio_analysis.png'
plt.savefig(output_path, dpi=300, bbox_inches='tight')
plt.show()
plt.close()

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Compare counts and shares for two categories in Excel data. The skill cleans the selected columns, calculates differences and percentages, and produces a summary spreadsheet plus bar and pie charts.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Comparing counts for two categories
  • Visualizing category shares
  • Cleaning merged-cell data before counting
OpenSenseNova/SenseNova-Skills5.8천2026년 10월 9일 업데이트

Analyze Excel data using custom categories, count distributions, and compare groups with charts. Score text using its length, technical terms, numbers, and selected complex concepts, then visualize difficulty levels and the relationship between text length and scores.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Summarize Excel records using custom categories
  • Compare category distributions across groups
  • Score and grade text using adjustable rules
OpenSenseNova/SenseNova-Skills5.8천2026년 10월 9일 업데이트

Count categories in a chosen data column after removing missing values and placeholder labels. Calculate each category’s share and create high-resolution charts combining counts, percentages, pie charts, and horizontal bars for distribution reports.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Compare record counts across categories
  • Show category shares with pie and bar charts
  • Exclude placeholder labels before counting
OpenSenseNova/SenseNova-Skills5.8천2026년 10월 9일 업데이트

Clean category and numeric fields in structured data, compare groups with counts and cross-tabulations, and produce charts, Excel results, and a Markdown report. Export visuals as high-resolution PNG and SVG files for use in reports.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Compare category distributions across groups
  • Clean category labels and fill merged-cell gaps
  • Export analysis results to Excel
OpenSenseNova/SenseNova-Skills5.8천2026년 10월 9일 업데이트

Filter Excel data using candidate column names, RGB color values, text prefixes, and regular expressions, which match text patterns. Calculate totals and averages, then export results to Excel with highlighted rows and a download link.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Filtering rows by RGB values or identifier prefixes
  • Converting text to numbers and calculating totals or averages
  • Extracting matching commands with their identifiers and descriptions
OpenSenseNova/SenseNova-Skills5.8천2026년 10월 9일 업데이트

Filter rows from Excel or previously converted Parquet files, a format designed for efficient data storage. Summarize matching records by group with counts, percentages, and totals, then export the summary to Excel.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Count records containing a specified risk level by work category
  • Calculate group shares among matching records
  • Summarize large datasets already converted to Parquet
OpenSenseNova/SenseNova-Skills5.8천2026년 10월 9일 업데이트

OpenSenseNova의 스킬 모두 보기

이 스킬의 문제 신고