Skip to content
Back to search

d3-viz

SkillWorks with Claude CodeGitHubIncomplete

Creating interactive data visualisations using d3.js. This skill should be used when creating custom charts, graphs, network diagrams, geographic visualisations, or any complex SVG-based data visualisation that requires fine-grained control over visual elements, transitions, or interactions. Use this for bespoke visualisations beyond standard charting libraries, whether in React, Vue, Svelte, vanilla JavaScript, or any other environment.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/chrisvoncsefalvay--claude-d3js-skill/badge.svg)](/listings/chrisvoncsefalvay--claude-d3js-skill)

HTML

<a href="/listings/chrisvoncsefalvay--claude-d3js-skill"><img src="/api/listings/chrisvoncsefalvay--claude-d3js-skill/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 820 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. ---
  2. name: d3-viz
  3. description: Creating interactive data visualisations using d3.js. This skill should be used when creating custom charts, graphs, network diagrams, geographic visualisations, or any complex SVG-based data visualisation that requires fine-grained control over visual elements, transitions, or interactions. Use this for bespoke visualisations beyond standard charting libraries, whether in React, Vue, Svelte, vanilla JavaScript, or any other environment.
  4. ---
  5. # D3.js Visualisation
  6. ## Overview
  7. 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.
  8. ## When to use d3.js
  9. **Use d3.js for:**
  10. - Custom visualisations requiring unique visual encodings or layouts
  11. - Interactive explorations with complex pan, zoom, or brush behaviours
  12. - Network/graph visualisations (force-directed layouts, tree diagrams, hierarchies, chord diagrams)
  13. - Geographic visualisations with custom projections
  14. - Visualisations requiring smooth, choreographed transitions
  15. - Publication-quality graphics with fine-grained styling control
  16. - Novel chart types not available in standard libraries
  17. **Consider alternatives for:**
  18. - 3D visualisations - use Three.js instead
  19. ## Core workflow
  20. ### 1. Set up d3.js
  21. Import d3 at the top of your script:
  22. ```javascript
  23. import * as d3 from 'd3';
  24. ```
  25. Or use the CDN version (7.x):
  26. ```html
  27. <script src="https://d3js.org/d3.v7.min.js"></script>
  28. ```
  29. All modules (scales, axes, shapes, transitions, etc.) are accessible through the `d3` namespace.
  30. ### 2. Choose the integration pattern
  31. **Pattern A: Direct DOM manipulation (recommended for most cases)**
  32. Use d3 to select DOM elements and manipulate them imperatively. This works in any JavaScript environment:
  33. ```javascript
  34. function drawChart(data) {
  35. if (!data || data.length === 0) return;
  36. const svg = d3.select('#chart'); // Select by ID, class, or DOM element
  37. // Clear previous content
  38. svg.selectAll("*").remove();
  39. // Set up dimensions
  40. const width = 800;
  41. const height = 400;
  42. const margin = { top: 20, right: 30, bottom: 40, left: 50 };
  43. // Create scales, axes, and draw visualisation
  44. // ... d3 code here ...
  45. }
  46. // Call when data changes
  47. drawChart(myData);
  48. ```
  49. **Pattern B: Declarative rendering (for frameworks with templating)**
  50. Use d3 for data calculations (scales, layouts) but render elements via your framework:
  51. ```javascript
  52. function getChartElements(data) {
  53. const xScale = d3.scaleLinear()
  54. .domain([0, d3.max(data, d => d.value)])
  55. .range([0, 400]);
  56. return data.map((d, i) => ({
  57. x: 50,
  58. y: i * 30,
  59. width: xScale(d.value),
  60. height: 25
  61. }));
  62. }
  63. // In React: {getChartElements(data).map((d, i) => <rect key={i} {...d} fill="steelblue" />)}
  64. // In Vue: v-for directive over the returned array
  65. // In vanilla JS: Create elements manually from the returned data
  66. ```
  67. 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.
  68. ### 3. Structure the visualisation code
  69. Follow this standard structure in your drawing function:
  70. ```javascript
  71. function drawVisualization(data) {
  72. if (!data || data.length === 0) return;
  73. const svg = d3.select('#chart'); // Or pass a selector/element
  74. svg.selectAll("*").remove(); // Clear previous render
  75. // 1. Define dimensions
  76. const width = 800;
  77. const height = 400;
  78. const margin = { top: 20, right: 30, bottom: 40, left: 50 };
  79. const innerWidth = width - margin.left - margin.right;
  80. const innerHeight = height - margin.top - margin.bottom;
  81. // 2. Create main group with margins
  82. const g = svg.append("g")
  83. .attr("transform", `translate(${margin.left},${margin.top})`);
  84. // 3. Create scales
  85. const xScale = d3.scaleLinear()
  86. .domain([0, d3.max(data, d => d.x)])
  87. .range([0, innerWidth]);
  88. const yScale = d3.scaleLinear()
  89. .domain([0, d3.max(data, d => d.y)])
  90. .range([innerHeight, 0]); // Note: inverted for SVG coordinates
  91. // 4. Create and append axes
  92. const xAxis = d3.axisBottom(xScale);
  93. const yAxis = d3.axisLeft(yScale);
  94. g.append("g")
  95. .attr("transform", `translate(0,${innerHeight})`)
  96. .call(xAxis);
  97. g.append("g")
  98. .call(yAxis);
  99. // 5. Bind data and create visual elements
  100. g.selectAll("circle")
  101. .data(data)
  102. .join("circle")
  103. .attr("cx", d => xScale(d.x))
  104. .attr("cy", d => yScale(d.y))
  105. .attr("r", 5)
  106. .attr("fill", "steelblue");
  107. }
  108. // Call when data changes
  109. drawVisualization(myData);
  110. ```
  111. ### 4. Implement responsive sizing
  112. Make visualisations responsive to container size:
  113. ```javascript
  114. function setupResponsiveChart(containerId, data) {
  115. const container = document.getElementById(containerId);
  116. const svg = d3.select(`#${containerId}`).append('svg');
  117. function updateChart() {
  118. const { width, height } = container.getBoundingClientRect();
  119. svg.attr('width', width).attr('height', height);
  120. // Redraw visualisation with new dimensions
  121. drawChart(data, svg, width, height);
  122. }
  123. // Update on initial load
  124. updateChart();
  125. // Update on window resize
  126. window.addEventListener('resize', updateChart);
  127. // Return cleanup function
  128. return () => window.removeEventListener('resize', updateChart);
  129. }
  130. // Usage:
  131. // const cleanup = setupResponsiveChart('chart-container', myData);
  132. // cleanup(); // Call when component unmounts or element removed
  133. ```
  134. Or use ResizeObserver for more direct container monitoring:
  135. ```javascript
  136. function setupResponsiveChartWithObserver(svgElement, data) {
  137. const observer = new ResizeObserver(() => {
  138. const { width, height } = svgElement.getBoundingClientRect();
  139. d3.select(svgElement)
  140. .attr('width', width)
  141. .attr('height', height);
  142. // Redraw visualisation
  143. drawChart(data, d3.select(svgElement), width, height);
  144. });
  145. observer.observe(svgElement.parentElement);
  146. return () => observer.disconnect();
  147. }
  148. ```
  149. ## Common visualisation patterns
  150. ### Bar chart
  151. ```javascript
  152. function drawBarChart(data, svgElement) {
  153. if (!data || data.length === 0) return;
  154. const svg = d3.select(svgElement);
  155. svg.selectAll("*").remove();
  156. const width = 800;
  157. const height = 400;
  158. const margin = { top: 20, right: 30, bottom: 40, left: 50 };
  159. const innerWidth = width - margin.left - margin.right;
  160. const innerHeight = height - margin.top - margin.bottom;
  161. const g = svg.append("g")
  162. .attr("transform", `translate(${margin.left},${margin.top})`);
  163. const xScale = d3.scaleBand()
  164. .domain(data.map(d => d.category))
  165. .range([0, innerWidth])
  166. .padding(0.1);
  167. const yScale = d3.scaleLinear()
  168. .domain([0, d3.max(data, d => d.value)])
  169. .range([innerHeight, 0]);
  170. g.append("g")
  171. .attr("transform", `translate(0,${innerHeight})`)
  172. .call(d3.axisBottom(xScale));
  173. g.append("g")
  174. .call(d3.axisLeft(yScale));
  175. g.selectAll("rect")
  176. .data(data)
  177. .join("rect")
  178. .attr("x", d => xScale(d.category))
  179. .attr("y", d => yScale(d.value))
  180. .attr("width", xScale.bandwidth())
  181. .attr("height", d => innerHeight - yScale(d.value))
  182. .attr("fill", "steelblue");
  183. }
  184. // Usage:
  185. // drawBarChart(myData, document.getElementById('chart'));
  186. ```
  187. ### Line chart
  188. ```javascript
  189. const line = d3.line()
  190. .x(d => xScale(d.date))
  191. .y(d => yScale(d.value))
  192. .curve(d3.curveMonotoneX); // Smooth curve
  193. g.append("path")
  194. .datum(data)
  195. .attr("fill", "none")
  196. .attr("stroke", "steelblue")
  197. .attr("stroke-width", 2)
  198. .attr("d", line);
  199. ```
  200. ### Scatter plot
  201. ```javascript
  202. g.selectAll("circle")
  203. .data(data)
  204. .join("circle")
  205. .attr("cx", d => xScale(d.x))
  206. .attr("cy", d => yScale(d.y))
  207. .attr("r", d => sizeScale(d.size)) // Optional: size encoding
  208. .attr("fill", d => colourScale(d.category)) // Optional: colour encoding
  209. .attr("opacity", 0.7);
  210. ```
  211. ### Chord diagram
  212. A chord diagram shows relationships between entities in a circular layout, with ribbons representing flows between them:
  213. ```javascript
  214. function drawChordDiagram(data) {
  215. // data format: array of objects with source, target, and value
  216. // Example: [{ source: 'A', target: 'B', value: 10 }, ...]
  217. if (!data || data.length === 0) return;
  218. const svg = d3.select('#chart');
  219. svg.selectAll("*").remove();
  220. const width = 600;
  221. const height = 600;
  222. const innerRadius = Math.min(width, height) * 0.3;
  223. const outerRadius = innerRadius + 30;
  224. // Create matrix from data
  225. const nodes = Array.from(new Set(data.flatMap(d => [d.source, d.target])));
  226. const matrix = Array.from({ length: nodes.length }, () => Array(nodes.length).fill(0));
  227. data.forEach(d => {
  228. const i = nodes.indexOf(d.source);
  229. const j = nodes.indexOf(d.target);
  230. matrix[i][j] += d.value;
  231. matrix[j][i] += d.value;
  232. });
  233. // Create chord layout
  234. const chord = d3.chord()
  235. .padAngle(0.05)
  236. .sortSubgroups(d3.descending);
  237. const arc = d3.arc()
  238. .innerRadius(innerRadius)
  239. .outerRadius(outerRadius);
  240. const ribbon = d3.ribbon()
  241. .source(d => d.source)
  242. .target(d => d.target);
  243. const colourScale = d3.scaleOrdinal(d3.schemeCategory10)
  244. .domain(nodes);
  245. const g = svg.append("g")
  246. .attr("transform", `translate(${width / 2},${height / 2})`);
  247. const chords = chord(matrix);
  248. // Draw ribbons
  249. g.append("g")
  250. .attr("fill-opacity", 0.67)
  251. .selectAll("path")
  252. .data(chords)
  253. .join("path")
  254. .attr("d", ribbon)
  255. .attr("fill", d => colourScale(nodes[d.source.index]))
  256. .attr("stroke", d => d3.rgb(colourScale(nodes[d.source.index])).darker());
  257. // Draw groups (arcs)
  258. const group = g.append("g")
  259. .selectAll("g")
  260. .data(chords.groups)
  261. .join("g");
  262. group.append("path")
  263. .attr("d", arc)
  264. .attr("fill", d => colourScale(nodes[d.index]))
  265. .attr("stroke", d => d3.rgb(colourScale(nodes[d.index])).darker());
  266. // Add labels
  267. group.append("text")
  268. .each(d => { d.angle = (d.startAngle + d.endAngle) / 2; })
  269. .attr("dy", "0.31em")
  270. .attr("transform", d => `rotate(${(d.angle * 180 / Math.PI) - 90})translate(${outerRadius + 30})${d.angle > Math.PI ? "rotate(180)" : ""}`)
  271. .attr("text-anchor", d => d.angle > Math.PI ? "end" : null)
  272. .text((d, i) => nodes[i])
  273. .style("font-size", "12px");
  274. }
  275. ```
  276. ### Heatmap
  277. A heatmap uses colour to encode values in a two-dimensional grid, useful for showing patterns across categories:
  278. ```javascript
  279. function drawHeatmap(data) {
  280. // data format: array of objects with row, column, and value
  281. // Example: [{ row: 'A', column: 'X', value: 10 }, ...]
  282. if (!data || data.length === 0) return;
  283. const svg = d3.select('#chart');
  284. svg.selectAll("*").remove();
  285. const width = 800;
  286. const height = 600;
  287. const margin = { top: 100, right: 30, bottom: 30, left: 100 };
  288. const innerWidth = width - margin.left - margin.right;
  289. const innerHeight = height - margin.top - margin.bottom;
  290. // Get unique rows and columns
  291. const rows = Array.from(new Set(data.map(d => d.row)));
  292. const columns = Array.from(new Set(data.map(d => d.column)));
  293. const g = svg.append("g")
  294. .attr("transform", `translate(${margin.left},${margin.top})`);
  295. // Create scales
  296. const xScale = d3.scaleBand()
  297. .domain(columns)
  298. .range([0, innerWidth])
  299. .padding(0.01);
  300. const yScale = d3.scaleBand()
  301. .domain(rows)
  302. .range([0, innerHeight])
  303. .padding(0.01);
  304. // Colour scale for values
  305. const colourScale = d3.scaleSequential(d3.interpolateYlOrRd)
  306. .domain([0, d3.max(data, d => d.value)]);
  307. // Draw rectangles
  308. g.selectAll("rect")
  309. .data(data)
  310. .join("rect")
  311. .attr("x", d => xScale(d.column))
  312. .attr("y", d => yScale(d.row))
  313. .attr("width", xScale.bandwidth())
  314. .attr("height", yScale.bandwidth())
  315. .attr("fill", d => colourScale(d.value));
  316. // Add x-axis labels
  317. svg.append("g")
  318. .attr("transform", `translate(${margin.left},${margin.top})`)
  319. .selectAll("text")
  320. .data(columns)
  321. .join("text")
  322. .attr("x", d => xScale(d) + xScale.bandwidth() / 2)
  323. .attr("y", -10)
  324. .attr("text-anchor", "middle")
  325. .text(d => d)
  326. .style("font-size", "12px");
  327. // Add y-axis labels
  328. svg.append("g")
  329. .attr("transform", `translate(${margin.left},${margin.top})`)
  330. .selectAll("text")
  331. .data(rows)
  332. .join("text")
  333. .attr("x", -10)
  334. .attr("y", d => yScale(d) + yScale.bandwidth() / 2)
  335. .attr("dy", "0.35em")
  336. .attr("text-anchor", "end")
  337. .text(d => d)
  338. .style("font-size", "12px");
  339. // Add colour legend
  340. const legendWidth = 20;
  341. const legendHeight = 200;
  342. const legend = svg.append("g")
  343. .attr("transform", `translate(${width - 60},${margin.top})`);
  344. const legendScale = d3.scaleLinear()
  345. .domain(colourScale.domain())
  346. .range([legendHeight, 0]);
  347. const legendAxis = d3.axisRight(legendScale)
  348. .ticks(5);
  349. // Draw colour gradient in legend
  350. for (let i = 0; i < legendHeight; i++) {
  351. legend.append("rect")
  352. .attr("y", i)
  353. .attr("width", legendWidth)
  354. .attr("height", 1)
  355. .attr("fill", colourScale(legendScale.invert(i)));
  356. }
  357. legend.append("g")
  358. .attr("transform", `translate(${legendWidth},0)`)
  359. .call(legendAxis);
  360. }
  361. ```
  362. ### Pie chart
  363. ```javascript
  364. const pie = d3.pie()
  365. .value(d => d.value)
  366. .sort(null);
  367. const arc = d3.arc()
  368. .innerRadius(0)
  369. .outerRadius(Math.min(width, height) / 2 - 20);
  370. const colourScale = d3.scaleOrdinal(d3.schemeCategory10);
  371. const g = svg.append("g")
  372. .attr("transform", `translate(${width / 2},${height / 2})`);
  373. g.selectAll("path")
  374. .data(pie(data))
  375. .join("path")
  376. .attr("d", arc)
  377. .attr("fill", (d, i) => colourScale(i))
  378. .attr("stroke", "white")
  379. .attr("stroke-width", 2);
  380. ```
  381. ### Force-directed network
  382. ```javascript
  383. const simulation = d3.forceSimulation(nodes)
  384. .force("link", d3.forceLink(links).id(d => d.id).distance(100))
  385. .force("charge", d3.forceManyBody().strength(-300))
  386. .force("center", d3.forceCenter(width / 2, height / 2));
  387. const link = g.selectAll("line")
  388. .data(links)
  389. .join("line")
  390. .attr("stroke", "#999")
  391. .attr("stroke-width", 1);
  392. const node = g.selectAll("circle")
  393. .data(nodes)
  394. .join("circle")
  395. .attr("r", 8)
  396. .attr("fill", "steelblue")
  397. .call(d3.drag()
  398. .on("start", dragstarted)
  399. .on("drag", dragged)
  400. .on("end", dragended));
  401. simulation.on("tick", () => {
  402. link
  403. .attr("x1", d => d.source.x)
  404. .attr("y1", d => d.source.y)
  405. .attr("x2", d => d.target.x)
  406. .attr("y2", d => d.target.y);
  407. node
  408. .attr("cx", d => d.x)
  409. .attr("cy", d => d.y);
  410. });
  411. function dragstarted(event) {
  412. if (!event.active) simulation.alphaTarget(0.3).restart();
  413. event.subject.fx = event.subject.x;
  414. event.subject.fy = event.subject.y;
  415. }
  416. function dragged(event) {
  417. event.subject.fx = event.x;
  418. event.subject.fy = event.y;
  419. }
  420. function dragended(event) {
  421. if (!event.active) simulation.alphaTarget(0);
  422. event.subject.fx = null;
  423. event.subject.fy = null;
  424. }
  425. ```
  426. ## Adding interactivity
  427. ### Tooltips
  428. ```javascript
  429. // Create tooltip div (outside SVG)
  430. const tooltip = d3.select("body").append("div")
  431. .attr("class", "tooltip")
  432. .style("position", "absolute")
  433. .style("visibility", "hidden")
  434. .style("background-color", "white")
  435. .style("border", "1px solid #ddd")
  436. .style("padding", "10px")
  437. .style("border-radius", "4px")
  438. .style("pointer-events", "none");
  439. // Add to elements
  440. circles
  441. .on("mouseover", function(event, d) {
  442. d3.select(this).attr("opacity", 1);
  443. tooltip
  444. .style("visibility", "visible")
  445. .html(`<strong>${d.label}</strong><br/>Value: ${d.value}`);
  446. })
  447. .on("mousemove", function(event) {
  448. tooltip
  449. .style("top", (event.pageY - 10) + "px")
  450. .style("left", (event.pageX + 10) + "px");
  451. })
  452. .on("mouseout", function() {
  453. d3.select(this).attr("opacity", 0.7);
  454. tooltip.style("visibility", "hidden");
  455. });
  456. ```
  457. ### Zoom and pan
  458. ```javascript
  459. const zoom = d3.zoom()
  460. .scaleExtent([0.5, 10])
  461. .on("zoom", (event) => {
  462. g.attr("transform", event.transform);
  463. });
  464. svg.call(zoom);
  465. ```
  466. ### Click interactions
  467. ```javascript
  468. circles
  469. .on("click", function(event, d) {
  470. // Handle click (dispatch event, update app state, etc.)
  471. console.log("Clicked:", d);
  472. // Visual feedback
  473. d3.selectAll("circle").attr("fill", "steelblue");
  474. d3.select(this).attr("fill", "orange");
  475. // Optional: dispatch custom event for your framework/app to listen to
  476. // window.dispatchEvent(new CustomEvent('chartClick', { detail: d }));
  477. });
  478. ```
  479. ## Transitions and animations
  480. Add smooth transitions to visual changes:
  481. ```javascript
  482. // Basic transition
  483. circles
  484. .transition()
  485. .duration(750)
  486. .attr("r", 10);
  487. // Chained transitions
  488. circles
  489. .transition()
  490. .duration(500)
  491. .attr("fill", "orange")
  492. .transition()
  493. .duration(500)
  494. .attr("r", 15);
  495. // Staggered transitions
  496. circles
  497. .transition()
  498. .delay((d, i) => i * 50)
  499. .duration(500)
  500. .attr("cy", d => yScale(d.value));
  501. // Custom easing
  502. circles
  503. .transition()
  504. .duration(1000)
  505. .ease(d3.easeBounceOut)
  506. .attr("r", 10);
  507. ```
  508. ## Scales reference
  509. ### Quantitative scales
  510. ```javascript
  511. // Linear scale
  512. const xScale = d3.scaleLinear()
  513. .domain([0, 100])
  514. .range([0, 500]);
  515. // Log scale (for exponential data)
  516. const logScale = d3.scaleLog()
  517. .domain([1, 1000])
  518. .range([0, 500]);
  519. // Power scale
  520. const powScale = d3.scalePow()
  521. .exponent(2)
  522. .domain([0, 100])
  523. .range([0, 500]);
  524. // Time scale
  525. const timeScale = d3.scaleTime()
  526. .domain([new Date(2020, 0, 1), new Date(2024, 0, 1)])
  527. .range([0, 500]);
  528. ```
  529. ### Ordinal scales
  530. ```javascript
  531. // Band scale (for bar charts)
  532. const bandScale = d3.scaleBand()
  533. .domain(['A', 'B', 'C', 'D'])
  534. .range([0, 400])
  535. .padding(0.1);
  536. // Point scale (for line/scatter categories)
  537. const pointScale = d3.scalePoint()
  538. .domain(['A', 'B', 'C', 'D'])
  539. .range([0, 400]);
  540. // Ordinal scale (for colours)
  541. const colourScale = d3.scaleOrdinal(d3.schemeCategory10);
  542. ```
  543. ### Sequential scales
  544. ```javascript
  545. // Sequential colour scale
  546. const colourScale = d3.scaleSequential(d3.interpolateBlues)
  547. .domain([0, 100]);
  548. // Diverging colour scale
  549. const divScale = d3.scaleDiverging(d3.interpolateRdBu)
  550. .domain([-10, 0, 10]);
  551. ```
  552. ## Best practices
  553. ### Data preparation
  554. Always validate and prepare data before visualisation:
  555. ```javascript
  556. // Filter invalid values
  557. const cleanData = data.filter(d => d.value != null && !isNaN(d.value));
  558. // Sort data if order matters
  559. const sortedData = [...data].sort((a, b) => b.value - a.value);
  560. // Parse dates
  561. const parsedData = data.map(d => ({
  562. ...d,
  563. date: d3.timeParse("%Y-%m-%d")(d.date)
  564. }));
  565. ```
  566. ### Performance optimisation
  567. For large datasets (>1000 elements):
  568. ```javascript
  569. // Use canvas instead of SVG for many elements
  570. // Use quadtree for collision detection
  571. // Simplify paths with d3.line().curve(d3.curveStep)
  572. // Implement virtual scrolling for large lists
  573. // Use requestAnimationFrame for custom animations
  574. ```
  575. ### Accessibility
  576. Make visualisations accessible:
  577. ```javascript
  578. // Add ARIA labels
  579. svg.attr("role", "img")
  580. .attr("aria-label", "Bar chart showing quarterly revenue");
  581. // Add title and description
  582. svg.append("title").text("Quarterly Revenue 2024");
  583. svg.append("desc").text("Bar chart showing revenue growth across four quarters");
  584. // Ensure sufficient colour contrast
  585. // Provide keyboard navigation for interactive elements
  586. // Include data table alternative
  587. ```
  588. ### Styling
  589. Use consistent, professional styling:
  590. ```javascript
  591. // Define colour palettes upfront
  592. const colours = {
  593. primary: '#4A90E2',
  594. secondary: '#7B68EE',
  595. background: '#F5F7FA',
  596. text: '#333333',
  597. gridLines: '#E0E0E0'
  598. };
  599. // Apply consistent typography
  600. svg.selectAll("text")
  601. .style("font-family", "Inter, sans-serif")
  602. .style("font-size", "12px");
  603. // Use subtle grid lines
  604. g.selectAll(".tick line")
  605. .attr("stroke", colours.gridLines)
  606. .attr("stroke-dasharray", "2,2");
  607. ```
  608. ## Common issues and solutions
  609. **Issue**: Axes not appearing
  610. - Ensure scales have valid domains (check for NaN values)
  611. - Verify axis is appended to correct group
  612. - Check transform translations are correct
  613. **Issue**: Transitions not working
  614. - Call `.transition()` before attribute changes
  615. - Ensure elements have unique keys for proper data binding
  616. - Check that useEffect dependencies include all changing data
  617. **Issue**: Responsive sizing not working
  618. - Use ResizeObserver or window resize listener
  619. - Update dimensions in state to trigger re-render
  620. - Ensure SVG has width/height attributes or viewBox
  621. **Issue**: Performance problems
  622. - Limit number of DOM elements (consider canvas for >1000 items)
  623. - Debounce resize handlers
  624. - Use `.join()` instead of separate enter/update/exit selections
  625. - Avoid unnecessary re-renders by checking dependencies
  626. ## Resources
  627. ### references/
  628. Contains detailed reference materials:
  629. - `d3-patterns.md` - Comprehensive collection of visualisation patterns and code examples
  630. - `scale-reference.md` - Complete guide to d3 scales with examples
  631. - `colour-schemes.md` - D3 colour schemes and palette recommendations
  632. ### assets/
  633. Contains boilerplate templates:
  634. - `chart-template.js` - Starter template for basic chart
  635. - `interactive-template.js` - Template with tooltips, zoom, and interactions
  636. - `sample-data.json` - Example datasets for testing
  637. These templates work with vanilla JavaScript, React, Vue, Svelte, or any other JavaScript environment. Adapt them as needed for your specific framework.
  638. To use these resources, read the relevant files when detailed guidance is needed for specific visualisation types or patterns.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.