يبقى الأمر في سطر واحد. مرّر أفقيًا لمراجعته كاملًا قبل النسخ.
تفضّل نسخة محلية؟ نزّل الملفات المتاحة حاليًا لدى SkillsMP.
مستكشف الملفات
7 ملفات
عرض SKILL.md
SKILL.md
تعليمات المصدر · معاينة للقراءة فقط
name
claude-d3js-skill
description
This skill provides guidance for creating sophisticated, interactive data visualisations using d3.js.
type
skill
created
2026-02-27T00:00:00.000Z
domain
ai-ml
category
llm-agents
risk
unknown
source
community
tags
["skill","ai-ml","llm-agents","claude","d3js"]
D3.js Visualisation
Overview
This skill provides guidance for creating sophisticated, interactive data visualisations using d3.js. D3.js (Data-Driven Documents) excels at binding data to DOM elements and applying data-driven transformations to create custom, publication-quality visualisations with precise control over every visual element. The techniques work across any JavaScript environment, including vanilla JavaScript, React, Vue, Svelte, and other frameworks.
When to use d3.js
Use d3.js for:
Custom visualisations requiring unique visual encodings or layouts
Interactive explorations with complex pan, zoom, or brush behaviours
Network/graph visualisations (force-directed layouts, tree diagrams, hierarchies, chord diagrams)
All modules (scales, axes, shapes, transitions, etc.) are accessible through the d3 namespace.
2. Choose the integration pattern
Pattern A: Direct DOM manipulation (recommended for most cases)
Use d3 to select DOM elements and manipulate them imperatively. This works in any JavaScript environment:
Pattern B: Declarative rendering (for frameworks with templating)
Use d3 for data calculations (scales, layouts) but render elements via your framework:
functiongetChartElements(data) {
const xScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)])
.range([0, 400]);
return data.map((d, i) => ({
x: 50,
y: i * 30,
width: xScale(d.value),
height: 25
}));
}
// In React: {getChartElements(data).map((d, i) => <rect key={i} {...d} fill="steelblue" />)}// In Vue: v-for directive over the returned array// In vanilla JS: Create elements manually from the returned data
Use Pattern A for complex visualisations with transitions, interactions, or when leveraging d3's full capabilities. Use Pattern B for simpler visualisations or when your framework prefers declarative rendering.
3. Structure the visualisation code
Follow this standard structure in your drawing function:
functiondrawVisualization(data) {
if (!data || data.length === 0) return;
const svg = d3.select('#chart'); // Or pass a selector/element
svg.selectAll("*").remove(); // Clear previous render// 1. Define dimensionsconst width = 800;
const height = 400;
const margin = { top: 20, right: 30, bottom: 40, left: 50 };
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
// 2. Create main group with marginsconst g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
// 3. Create scalesconst xScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.x)])
.range([0, innerWidth]);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.y)])
.range([innerHeight, 0]); // Note: inverted for SVG coordinates// 4. Create and append axesconst xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
g.append("g")
.attr("transform", `translate(0,${innerHeight})`)
.call(xAxis);
g.append("g")
.call(yAxis);
// 5. Bind data and create visual elements
g.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", d =>xScale(d.x))
.attr("cy", d =>yScale(d.y))
.attr("r", 5)
.attr("fill", "steelblue");
}
// Call when data changesdrawVisualization(myData);
4. Implement responsive sizing
Make visualisations responsive to container size:
functionsetupResponsiveChart(containerId, data) {
const container = document.getElementById(containerId);
const svg = d3.select(`#${containerId}`).append('svg');
functionupdateChart() {
const { width, height } = container.getBoundingClientRect();
svg.attr('width', width).attr('height', height);
// Redraw visualisation with new dimensionsdrawChart(data, svg, width, height);
}
// Update on initial loadupdateChart();
// Update on window resizewindow.addEventListener('resize', updateChart);
// Return cleanup functionreturn() =>window.removeEventListener('resize', updateChart);
}
// Usage:// const cleanup = setupResponsiveChart('chart-container', myData);// cleanup(); // Call when component unmounts or element removed
Or use ResizeObserver for more direct container monitoring:
Always validate and prepare data before visualisation:
// Filter invalid valuesconst cleanData = data.filter(d => d.value != null && !isNaN(d.value));
// Sort data if order mattersconst sortedData = [...data].sort((a, b) => b.value - a.value);
// Parse datesconst parsedData = data.map(d => ({
...d,
date: d3.timeParse("%Y-%m-%d")(d.date)
}));
Performance optimisation
For large datasets (>1000 elements):
// Use canvas instead of SVG for many elements// Use quadtree for collision detection// Simplify paths with d3.line().curve(d3.curveStep)// Implement virtual scrolling for large lists// Use requestAnimationFrame for custom animations
Accessibility
Make visualisations accessible:
// Add ARIA labels
svg.attr("role", "img")
.attr("aria-label", "Bar chart showing quarterly revenue");
// Add title and description
svg.append("title").text("Quarterly Revenue 2024");
svg.append("desc").text("Bar chart showing revenue growth across four quarters");
// Ensure sufficient colour contrast// Provide keyboard navigation for interactive elements// Include data table alternative
Ensure scales have valid domains (check for NaN values)
Verify axis is appended to correct group
Check transform translations are correct
Issue: Transitions not working
Call .transition() before attribute changes
Ensure elements have unique keys for proper data binding
Check that useEffect dependencies include all changing data
Issue: Responsive sizing not working
Use ResizeObserver or window resize listener
Update dimensions in state to trigger re-render
Ensure SVG has width/height attributes or viewBox
Issue: Performance problems
Limit number of DOM elements (consider canvas for >1000 items)
Debounce resize handlers
Use .join() instead of separate enter/update/exit selections
Avoid unnecessary re-renders by checking dependencies
Resources
references/
Contains detailed reference materials:
d3-patterns.md - Comprehensive collection of visualisation patterns and code examples
scale-reference.md - Complete guide to d3 scales with examples
colour-schemes.md - D3 colour schemes and palette recommendations
assets/
Contains boilerplate templates:
chart-template.js - Starter template for basic chart
interactive-template.js - Template with tooltips, zoom, and interactions
sample-data.json - Example datasets for testing
These templates work with vanilla JavaScript, React, Vue, Svelte, or any other JavaScript environment. Adapt them as needed for your specific framework.
To use these resources, read the relevant files when detailed guidance is needed for specific visualisation types or patterns.