{
  "schema": "https://ai-atoms.com/schemas/skill-v1.json",
  "type": "skill",
  "id": "skill/data-visualization",
  "version": "1.0.0",
  "name": "data-visualization",
  "description": "Create effective data visualizations with Python (matplotlib, seaborn, plotly). Use when building charts, choosing the right chart type for a dataset, creating publication-quality figures, or applying design principles like accessibility and color theory.",
  "system_prompt_fragment": "# Data Visualization Skill\n\nChart selection guidance, Python visualization code patterns, design principles, and accessibility considerations for creating effective data visualizations.\n\n## Chart Selection Guide\n\n### Choose by Data Relationship\n\n| What You're Showing | Best Chart | Alternatives |\n|---|---|---|\n| **Trend over time** | Line chart | Area chart (if showing cumulative or composition) |\n| **Comparison across categories** | Vertical bar chart | Horizontal bar (many categories), lollipop chart |\n| **Ranking** | Horizontal bar chart | Dot plot, slope chart (comparing two periods) |\n| **Part-to-whole composition** | Stacked bar chart | Treemap (hierarchical), waffle chart |\n| **Composition over time** | Stacked area chart | 100% stacked bar (for proportion focus) |\n| **Distribution** | Histogram | Box plot (comparing groups), violin plot, strip plot |\n| **Correlation (2 variables)** | Scatter plot | Bubble chart (add 3rd variable as size) |\n| **Correlation (many variables)** | Heatmap (correlation matrix) | Pair plot |\n| **Geographic patterns** | Choropleth map | Bubble map, hex map |\n| **Flow / process** | Sankey diagram | Funnel chart (sequential stages) |\n| **Relationship network** | Network graph | Chord diagram |\n| **Performance vs. target** | Bullet chart | Gauge (single KPI only) |\n| **Multiple KPIs at once** | Small multiples | Dashboard with separate charts |\n\n### When NOT to Use Certain Charts\n\n- **Pie charts**: Avoid unless <6 categories and exact proportions matter less than rough comparison. Humans are bad at comparing angles. Use bar charts instead.\n- **3D charts**: Never. They distort perception and add no information.\n- **Dual-axis charts**: Use cautiously. They can mislead by implying correlation. Clearly label both axes if used.\n- **Stacked bar (many categories)**: Hard to compare middle segments. Use small multiples or grouped bars instead.\n- **Donut charts**: Slightly better than pie charts but same fundamental issues. Use for single KPI display at most.\n\n## Python Visualization Code Patterns\n\n### Setup and Style\n\n```python\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mticker\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\n\n# Professional style setup\nplt.style.use('seaborn-v0_8-whitegrid')\nplt.rcParams.update({\n    'figure.figsize': (10, 6),\n    'figure.dpi': 150,\n    'font.size': 11,\n    'axes.titlesize': 14,\n    'axes.titleweight': 'bold',\n    'axes.labelsize': 11,\n    'xtick.labelsize': 10,\n    'ytick.labelsize': 10,\n    'legend.fontsize': 10,\n    'figure.titlesize': 16,\n})\n\n# Colorblind-friendly palettes\nPALETTE_CATEGORICAL = ['#4C72B0', '#DD8452', '#55A868', '#C44E52', '#8172B3', '#937860']\nPALETTE_SEQUENTIAL = 'YlOrRd'\nPALETTE_DIVERGING = 'RdBu_r'\n```\n\n### Line Chart (Time Series)\n\n```python\nfig, ax = plt.subplots(figsize=(10, 6))\n\nfor label, group in df.groupby('category'):\n    ax.plot(group['date'], group['value'], label=label, linewidth=2)\n\nax.set_title('Metric Trend by Category', fontweight='bold')\nax.set_xlabel('Date')\nax.set_ylabel('Value')\nax.legend(loc='upper left', frameon=True)\nax.spines['top'].set_visible(False)\nax.spines['right'].set_visible(False)\n\n# Format dates on x-axis\nfig.autofmt_xdate()\n\nplt.tight_layout()\nplt.savefig('trend_chart.png', dpi=150, bbox_inches='tight')\n```\n\n### Bar Chart (Comparison)\n\n```python\nfig, ax = plt.subplots(figsize=(10, 6))\n\n# Sort by value for easy reading\ndf_sorted = df.sort_values('metric', ascending=True)\n\nbars = ax.barh(df_sorted['category'], df_sorted['metric'], color=PALETTE_CATEGORICAL[0])\n\n# Add value labels\nfor bar in bars:\n    width = bar.get_width()\n    ax.text(width + 0.5, bar.get_y() + bar.get_height()/2,\n            f'{width:,.0f}', ha='left', va='center', fontsize=10)\n\nax.set_title('Metric by Category (Ranked)', fontweight='bold')\nax.set_xlabel('Metric Value')\nax.spines['top'].set_visible(False)\nax.spines['right'].set_visible(False)\n\nplt.tight_layout()\nplt.savefig('bar_chart.png', dpi=150, bbox_inches='tight')\n```\n\n### Histogram (Distribution)\n\n```python\nfig, ax = plt.subplots(figsize=(10, 6))\n\nax.hist(df['value'], bins=30, color=PALETTE_CATEGORICAL[0], edgecolor='white', alpha=0.8)\n\n# Add mean and median lines\nmean_val = df['value'].mean()\nmedian_val = df['value'].median()\nax.axvline(mean_val, color='red', linestyle='--', linewidth=1.5, label=f'Mean: {mean_val:,.1f}')\nax.axvline(median_val, color='green', linestyle='--', linewidth=1.5, label=f'Median: {median_val:,.1f}')\n\nax.set_title('Distribution of Values', fontweight='bold')\nax.set_xlabel('Value')\nax.set_ylabel('Frequency')\nax.legend()\nax.spines['top'].set_visible(False)\nax.spines['right'].set_visible(False)\n\nplt.tight_layout()\nplt.savefig('histogram.png', dpi=150, bbox_inches='tight')\n```\n\n### Heatmap\n\n```python\nfig, ax = plt.subplots(figsize=(10, 8))\n\n# Pivot data for heatmap format\npivot = df.pivot_table(index='row_dim', columns='col_dim', values='metric', aggfunc='sum')\n\nsns.heatmap(pivot, annot=True, fmt=',.0f', cmap='YlOrRd',\n            linewidths=0.5, ax=ax, cbar_kws={'label': 'Metric Value'})\n\nax.set_title('Metric by Row Dimension and Column Dimension', fontweight='bold')\nax.set_xlabel('Column Dimension')\nax.set_ylabel('Row Dimension')\n\nplt.tight_layout()\nplt.savefig('heatmap.png', dpi=150, bbox_inches='tight')\n```\n\n### Small Multiples\n\n```python\ncategories = df['category'].unique()\nn_cats = len(categories)\nn_cols = min(3, n_cats)\nn_rows = (n_cats + n_cols - 1) // n_cols\n\nfig, axes = plt.subplots(n_rows, n_cols, figsize=(5*n_cols, 4*n_rows), sharex=True, sharey=True)\naxes = axes.flatten() if n_cats > 1 else [axes]\n\nfor i, cat in enumerate(categories):\n    ax = axes[i]\n    subset = df[df['category'] == cat]\n    ax.plot(subset['date'], subset['value'], color=PALETTE_CATEGORICAL[i % len(PALETTE_CATEGORICAL)])\n    ax.set_title(cat, fontsize=12)\n    ax.spines['top'].set_visible(False)\n    ax.spines['right'].set_visible(False)\n\n# Hide empty subplots\nfor j in range(i+1, len(axes)):\n    axes[j].set_visible(False)\n\nfig.suptitle('Trends by Category', fontsize=14, fontweight='bold', y=1.02)\nplt.tight_layout()\nplt.savefig('small_multiples.png', dpi=150, bbox_inches='tight')\n```\n\n### Number Formatting Helpers\n\n```python\ndef format_number(val, format_type='number'):\n    \"\"\"Format numbers for chart labels.\"\"\"\n    if format_type == 'currency':\n        if abs(val) >= 1e9:\n            return f'${val/1e9:.1f}B'\n        elif abs(val) >= 1e6:\n            return f'${val/1e6:.1f}M'\n        elif abs(val) >= 1e3:\n            return f'${val/1e3:.1f}K'\n        else:\n            return f'${val:,.0f}'\n    elif format_type == 'percent':\n        return f'{val:.1f}%'\n    elif format_type == 'number':\n        if abs(val) >= 1e9:\n            return f'{val/1e9:.1f}B'\n        elif abs(val) >= 1e6:\n            return f'{val/1e6:.1f}M'\n        elif abs(val) >= 1e3:\n            return f'{val/1e3:.1f}K'\n        else:\n            return f'{val:,.0f}'\n    return str(val)\n\n# Usage with axis formatter\nax.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, p: format_number(x, 'currency')))\n```\n\n### Interactive Charts with Plotly\n\n```python\nimport plotly.express as px\nimport plotly.graph_objects as go\n\n# Simple interactive line chart\nfig = px.line(df, x='date', y='value', color='category',\n              title='Interactive Metric Trend',\n              labels={'value': 'Metric Value', 'date': 'Date'})\nfig.update_layout(hovermode='x unified')\nfig.write_html('interactive_chart.html')\nfig.show()\n\n# Interactive scatter with hover data\nfig = px.scatter(df, x='metric_a', y='metric_b', color='category',\n                 size='size_metric', hover_data=['name', 'detail_field'],\n                 title='Correlation Analysis')\nfig.show()\n```\n\n## Design Principles\n\n### Color\n\n- **Use color purposefully**: Color should encode data, not decorate\n- **Highlight the story**: Use a bright accent color for the key insight; grey everything else\n- **Sequential data**: Use a single-hue gradient (light to dark) for ordered values\n- **Diverging data**: Use a two-hue gradient with neutral midpoint for data with a meaningful center\n- **Categorical data**: Use distinct hues, maximum 6-8 before it gets confusing\n- **Avoid red/green only**: 8% of men are red-green colorblind. Use blue/orange as primary pair\n\n### Typography\n\n- **Title states the insight**: \"Revenue grew 23% YoY\" beats \"Revenue by Month\"\n- **Subtitle adds context**: Date range, filters applied, data source\n- **Axis labels are readable**: Never rotated 90 degrees if avoidable. Shorten or wrap instead\n- **Data labels add precision**: Use on key points, not every single bar\n- **Annotation highlights**: Call out specific points with text annotations\n\n### Layout\n\n- **Reduce chart junk**: Remove gridlines, borders, backgrounds that don't carry information\n- **Sort meaningfully**: Categories sorted by value (not alphabetically) unless there's a natural order (months, stages)\n- **Appropriate aspect ratio**: Time series wider than tall (3:1 to 2:1); comparisons can be squarer\n- **White space is good**: Don't cram charts together. Give each visualization room to breathe\n\n### Accuracy\n\n- **Bar charts start at zero**: Always. A bar from 95 to 100 exaggerates a 5% difference\n- **Line charts can have non-zero baselines**: When the range of variation is meaningful\n- **Consistent scales across panels**: When comparing multiple charts, use the same axis range\n- **Show uncertainty**: Error bars, confidence intervals, or ranges when data is uncertain\n- **Label your axes**: Never make the reader guess what the numbers mean\n\n## Accessibility Considerations\n\n### Color Blindness\n\n- Never rely on color alone to distinguish data series\n- Add pattern fills, different line styles (solid, dashed, dotted), or direct labels\n- Test with a colorblind simulator (e.g., Coblis, Sim Daltonism)\n- Use the colorblind-friendly palette: `sns.color_palette(\"colorblind\")`\n\n### Screen Readers\n\n- Include alt text describing the chart's key finding\n- Provide a data table alternative alongside the visualization\n- Use semantic titles and labels\n\n### General Accessibility\n\n- Sufficient contrast between data elements and background\n- Text size minimum 10pt for labels, 12pt for titles\n- Avoid conveying information only through spatial position (add labels)\n- Consider printing: does the chart work in black and white?\n\n### Accessibility Checklist\n\nBefore sharing a visualization:\n- [ ] Chart works without color (patterns, labels, or line styles differentiate series)\n- [ ] Text is readable at standard zoom level\n- [ ] Title describes the insight, not just the data\n- [ ] Axes are labeled with units\n- [ ] Legend is clear and positioned without obscuring data\n- [ ] Data source and date range are noted",
  "applicable_domains": [
    "data",
    "analytics"
  ],
  "invocation": [
    "/data-visualization"
  ],
  "tags": [
    "data",
    "anthropics",
    "knowledge-work"
  ],
  "authored_by": "anthropics",
  "source_url": "https://github.com/anthropics/knowledge-work-plugins/blob/main/data/skills/data-visualization/SKILL.md",
  "lifecycle": "stable",
  "category": "data",
  "provenance": {
    "source": "anthropics/knowledge-work-plugins",
    "source_url": "https://github.com/anthropics/knowledge-work-plugins/blob/main/data/skills/data-visualization/SKILL.md",
    "author": "Anthropic",
    "license": "Apache-2.0",
    "notes": "Imported by scripts/import-anthropic-skills.py."
  }
}