---
name: data-analysis
description: "Analyze data from various sources and generate visualizations with Chinese label support."
whenToUse: "User asks to analyze data, metrics, or trends"
---

# Skill: Data Analysis & Visualization

## Description
Analyze data from various sources (CSV, Excel, JSON, APIs) and generate visualizations (charts, graphs, tables) with Chinese label support. Output as images, PDFs, or Excel files.

## When to Use
- User asks to analyze data, metrics, or trends
- User asks to create charts, graphs, or dashboards
- User wants to compare numbers, compute statistics
- User says "帮我分析" or "做个图表"

## Prerequisites
- Python: pandas, matplotlib, numpy (confirmed available)
- Optional: openpyxl (for Excel), seaborn (for advanced plots)

## Steps

### 1. Chinese Font Setup for Matplotlib
```python
import matplotlib.pyplot as plt
import matplotlib

# Set Chinese font
matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei']
matplotlib.rcParams['axes.unicode_minus'] = False  # Fix minus sign
```

### 2. Read Data
```python
import pandas as pd

# CSV
df = pd.read_csv('data.csv')

# Excel
df = pd.read_excel('data.xlsx', sheet_name='Sheet1')

# JSON
df = pd.read_json('data.json')

# From clipboard
df = pd.read_clipboard()
```

### 3. Quick Analysis
```python
# Overview
print(df.shape)           # (rows, cols)
print(df.describe())      # Statistics
print(df.info())          # Types & nulls
print(df.head(10))        # Preview

# Group by
summary = df.groupby('category').agg({'value': ['mean', 'sum', 'count']})

# Pivot table
pivot = pd.pivot_table(df, values='value', index='date', columns='category', aggfunc='mean')
```

### 4. Visualization Templates

#### Bar Chart
```python
fig, ax = plt.subplots(figsize=(10, 6))
df.plot(kind='bar', x='category', y='value', ax=ax, color='#1a73e8')
ax.set_title('标题', fontsize=16, fontweight='bold')
ax.set_xlabel('类别')
ax.set_ylabel('数值')
plt.tight_layout()
plt.savefig('chart.png', dpi=150, bbox_inches='tight')
```

#### Line Chart (Time Series)
```python
fig, ax = plt.subplots(figsize=(12, 6))
for col in columns:
    ax.plot(df['date'], df[col], marker='o', label=col)
ax.legend()
ax.set_title('趋势分析')
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('trend.png', dpi=150)
```

#### Pie Chart
```python
fig, ax = plt.subplots(figsize=(8, 8))
ax.pie(values, labels=labels, autopct='%1.1f%%', colors=palette)
ax.set_title('占比分析')
plt.savefig('pie.png', dpi=150)
```

#### Heatmap
```python
import seaborn as sns
fig, ax = plt.subplots(figsize=(10, 8))
sns.heatmap(correlation_matrix, annot=True, cmap='RdYlBu_r', center=0, ax=ax)
plt.tight_layout()
plt.savefig('heatmap.png', dpi=150)
```

### 5. Output Options
- **PNG image**: `plt.savefig('chart.png', dpi=150)` — good for quick sharing
- **PDF report**: Combine with create-pdf-report skill
- **Excel**: `df.to_excel('output.xlsx', index=False)`
- **HTML table**: `df.to_html('table.html')`

### 6. Color Palettes
```python
# Microsoft-style
MS_COLORS = ['#1a73e8', '#e94560', '#27ae60', '#f39c12', '#9b59b6', '#1abc9c']

# Muted professional
PRO_COLORS = ['#264653', '#2a9d8f', '#e9c46a', '#f4a261', '#e76f51']
```

## Important Notes
- Always use `sys.stdout.reconfigure(encoding='utf-8')` for Chinese output
- Save charts to Desktop or Temp for bridge auto-send
- Close figures after saving: `plt.close(fig)` to avoid memory leaks
- For large datasets, sample first: `df.sample(1000)` for visualization
