d3js-visualization
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseD3.js Data Visualization Skill
D3.js 数据可视化技能
What is D3.js
什么是D3.js
D3.js (Data-Driven Documents) is a JavaScript library for producing dynamic, interactive data visualizations in web browsers. It uses HTML, SVG, and CSS standards to bind data to the DOM and apply data-driven transformations.
D3.js(Data-Driven Documents,数据驱动文档)是一款用于在网页浏览器中生成动态、交互式数据可视化效果的JavaScript库。它采用HTML、SVG和CSS标准将数据绑定到DOM,并应用数据驱动的转换。
When to Use D3.js
何时使用D3.js
Choose D3.js when you need:
- Custom, unique visualizations not available in chart libraries
- Fine-grained control over every visual element
- Complex interactions and animations
- Data-driven DOM manipulation beyond just charts
- Performance with large datasets (when using Canvas)
- Web standards-based visualizations
Consider alternatives when:
- Simple standard charts are sufficient (use Chart.js, Plotly)
- Quick prototyping is priority (use Observable, Vega-Lite)
- Static charts for print/reports (use matplotlib, ggplot2)
- 3D visualizations (use Three.js, WebGL libraries)
当你需要以下功能时选择D3.js:
- 图表库中没有的自定义、独特可视化效果
- 对每个视觉元素进行精细控制
- 复杂的交互和动画效果
- 超出普通图表的数据驱动DOM操作
- 处理大型数据集时的高性能(使用Canvas时)
- 基于Web标准的可视化效果
考虑替代方案的场景:
- 仅需简单标准图表(使用Chart.js、Plotly)
- 优先快速原型开发(使用Observable、Vega-Lite)
- 用于打印/报告的静态图表(使用matplotlib、ggplot2)
- 3D可视化效果(使用Three.js、WebGL库)
D3.js vs Other Libraries
D3.js 与其他库对比
| Library | Best For | Learning Curve | Customization |
|---|---|---|---|
| D3.js | Custom visualizations | Steep | Complete |
| Chart.js | Standard charts | Easy | Limited |
| Plotly | Scientific plots | Medium | Good |
| Highcharts | Business dashboards | Easy | Good |
| Three.js | 3D graphics | Steep | Complete |
| 库 | 最佳适用场景 | 学习曲线 | 自定义程度 |
|---|---|---|---|
| D3.js | 自定义可视化 | 陡峭 | 完全自定义 |
| Chart.js | 标准图表 | 简单 | 有限 |
| Plotly | 科学绘图 | 中等 | 良好 |
| Highcharts | 商业仪表盘 | 简单 | 良好 |
| Three.js | 3D图形 | 陡峭 | 完全自定义 |
Core Workflow
核心工作流程
1. Project Setup
1. 项目搭建
Option 1: CDN (Quick Start)
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3 Visualization</title>
<style>
body { margin: 0; font-family: sans-serif; }
svg { display: block; }
</style>
</head>
<body>
<div id="chart"></div>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script>
// Your code here
</script>
</body>
</html>Option 2: NPM (Production)
bash
npm install d3javascript
// Import all of D3
import * as d3 from "d3";
// Or import specific modules
import { select, selectAll } from "d3-selection";
import { scaleLinear, scaleTime } from "d3-scale";选项1:CDN(快速开始)
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3 Visualization</title>
<style>
body { margin: 0; font-family: sans-serif; }
svg { display: block; }
</style>
</head>
<body>
<div id="chart"></div>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script>
// Your code here
</script>
</body>
</html>选项2:NPM(生产环境)
bash
npm install d3javascript
// Import all of D3
import * as d3 from "d3";
// Or import specific modules
import { select, selectAll } from "d3-selection";
import { scaleLinear, scaleTime } from "d3-scale";2. Create Basic Chart
2. 创建基础图表
javascript
// Set up dimensions and margins
const margin = {top: 20, right: 30, bottom: 40, left: 50};
const width = 800 - margin.left - margin.right;
const height = 400 - margin.top - margin.bottom;
// Create SVG
const svg = d3.select("#chart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
// Load and process data
d3.csv("data.csv", d => ({
date: new Date(d.date),
value: +d.value
})).then(data => {
// Create scales
const xScale = d3.scaleTime()
.domain(d3.extent(data, d => d.date))
.range([0, width]);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)])
.nice()
.range([height, 0]);
// Create and append axes
svg.append("g")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(xScale));
svg.append("g")
.call(d3.axisLeft(yScale));
// Create line generator
const line = d3.line()
.x(d => xScale(d.date))
.y(d => yScale(d.value))
.curve(d3.curveMonotoneX);
// Draw line
svg.append("path")
.datum(data)
.attr("d", line)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 2);
});javascript
// Set up dimensions and margins
const margin = {top: 20, right: 30, bottom: 40, left: 50};
const width = 800 - margin.left - margin.right;
const height = 400 - margin.top - margin.bottom;
// Create SVG
const svg = d3.select("#chart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
// Load and process data
d3.csv("data.csv", d => ({
date: new Date(d.date),
value: +d.value
})).then(data => {
// Create scales
const xScale = d3.scaleTime()
.domain(d3.extent(data, d => d.date))
.range([0, width]);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)])
.nice()
.range([height, 0]);
// Create and append axes
svg.append("g")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(xScale));
svg.append("g")
.call(d3.axisLeft(yScale));
// Create line generator
const line = d3.line()
.x(d => xScale(d.date))
.y(d => yScale(d.value))
.curve(d3.curveMonotoneX);
// Draw line
svg.append("path")
.datum(data)
.attr("d", line)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 2);
});3. Add Interactivity
3. 添加交互效果
Tooltips:
javascript
const tooltip = d3.select("body")
.append("div")
.attr("class", "tooltip")
.style("position", "absolute")
.style("visibility", "hidden")
.style("background", "white")
.style("border", "1px solid #ddd")
.style("padding", "10px")
.style("border-radius", "4px");
circles
.on("mouseover", function(event, d) {
tooltip
.style("visibility", "visible")
.html(`<strong>${d.name}</strong><br/>Value: ${d.value}`);
})
.on("mousemove", function(event) {
tooltip
.style("top", (event.pageY - 10) + "px")
.style("left", (event.pageX + 10) + "px");
})
.on("mouseout", function() {
tooltip.style("visibility", "hidden");
});Transitions:
javascript
circles
.transition()
.duration(300)
.ease(d3.easeCubicOut)
.attr("r", 8);工具提示:
javascript
const tooltip = d3.select("body")
.append("div")
.attr("class", "tooltip")
.style("position", "absolute")
.style("visibility", "hidden")
.style("background", "white")
.style("border", "1px solid #ddd")
.style("padding", "10px")
.style("border-radius", "4px");
circles
.on("mouseover", function(event, d) {
tooltip
.style("visibility", "visible")
.html(`<strong>${d.name}</strong><br/>Value: ${d.value}`);
})
.on("mousemove", function(event) {
tooltip
.style("top", (event.pageY - 10) + "px")
.style("left", (event.pageX + 10) + "px");
})
.on("mouseout", function() {
tooltip.style("visibility", "hidden");
});过渡动画:
javascript
circles
.transition()
.duration(300)
.ease(d3.easeCubicOut)
.attr("r", 8);4. Implement Responsive Design
4. 实现响应式设计
javascript
function createChart() {
const container = d3.select("#chart");
const containerWidth = container.node().getBoundingClientRect().width;
const margin = {top: 20, right: 30, bottom: 40, left: 50};
const width = containerWidth - margin.left - margin.right;
const height = Math.min(width * 0.6, 500);
container.selectAll("*").remove(); // Clear previous
// Create SVG...
}
// Initial render
createChart();
// Re-render on resize with debouncing
let resizeTimer;
window.addEventListener("resize", () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(createChart, 250);
});javascript
function createChart() {
const container = d3.select("#chart");
const containerWidth = container.node().getBoundingClientRect().width;
const margin = {top: 20, right: 30, bottom: 40, left: 50};
const width = containerWidth - margin.left - margin.right;
const height = Math.min(width * 0.6, 500);
container.selectAll("*").remove(); // Clear previous
// Create SVG...
}
// Initial render
createChart();
// Re-render on resize with debouncing
let resizeTimer;
window.addEventListener("resize", () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(createChart, 250);
});Key Principles
核心原则
Data Binding
数据绑定
- Use to bind data to DOM elements
.data() - Handle enter, update, and exit selections
- Use key functions for consistent element-to-data matching
- Modern syntax: use for cleaner code
.join()
- 使用将数据绑定到DOM元素
.data() - 处理enter、update和exit选择集
- 使用键函数实现元素与数据的一致匹配
- 现代语法:使用简化代码
.join()
Scales
比例尺
- Map data values (domain) to visual values (range)
- Use appropriate scale types (linear, time, band, ordinal)
- Apply to scales for rounded axis values
.nice() - Invert y-scale range for bottom-up coordinates:
[height, 0]
- 将数据值(定义域)映射为视觉值(值域)
- 使用合适的比例尺类型(线性、时间、带状、序数)
- 对比例尺应用以获得轴的整数值
.nice() - 反转y轴值域实现自下而上的坐标:
[height, 0]
SVG Coordinate System
SVG坐标系
- Origin (0,0) is at top-left corner
- Y increases downward (opposite of Cartesian)
- Use margin convention for proper spacing
- Group related elements with tags
<g>
- 原点(0,0)位于左上角
- Y轴向下递增(与笛卡尔坐标系相反)
- 使用边距约定确保合理间距
- 使用标签分组相关元素
<g>
Performance
性能优化
- Use SVG for <1,000 elements
- Use Canvas for >1,000 elements
- Aggregate or sample large datasets
- Debounce resize handlers
- 元素数量<1000时使用SVG
- 元素数量>1000时使用Canvas
- 对大型数据集进行聚合或采样
- 防抖处理 resize 事件处理器
Chart Selection Guide
图表选择指南
Time series data? → Line chart or area chart
Comparing categories? → Bar chart (vertical or horizontal)
Showing relationships? → Scatter plot or bubble chart
Part-to-whole? → Donut chart or stacked bar (limit to 5-7 categories)
Network data? → Force-directed graph
Distribution? → Histogram or box plot
See for detailed chart selection criteria and best practices.
references/chart-types.md处理时间序列数据? → 折线图或面积图
比较分类数据? → 柱状图(垂直或水平)
展示数据关系? → 散点图或气泡图
展示部分与整体关系? → 环形图或堆叠柱状图(分类数量限制在5-7个)
处理网络数据? → 力导向图
展示数据分布? → 直方图或箱线图
详细的图表选择标准及最佳实践请参考。
references/chart-types.mdCommon Patterns
常见模式
Quick Data Loading
快速加载数据
javascript
// Load CSV with type conversion
d3.csv("data.csv", d => ({
date: new Date(d.date),
value: +d.value,
category: d.category
})).then(data => {
createChart(data);
});javascript
// Load CSV with type conversion
d3.csv("data.csv", d => ({
date: new Date(d.date),
value: +d.value,
category: d.category
})).then(data => {
createChart(data);
});Quick Tooltip
快速实现工具提示
javascript
selection
.on("mouseover", (event, d) => {
tooltip.style("visibility", "visible").html(`Value: ${d.value}`);
})
.on("mousemove", (event) => {
tooltip.style("top", event.pageY + "px").style("left", event.pageX + "px");
})
.on("mouseout", () => tooltip.style("visibility", "hidden"));javascript
selection
.on("mouseover", (event, d) => {
tooltip.style("visibility", "visible").html(`Value: ${d.value}`);
})
.on("mousemove", (event) => {
tooltip.style("top", event.pageY + "px").style("left", event.pageX + "px");
})
.on("mouseout", () => tooltip.style("visibility", "hidden"));Quick Responsive SVG
快速实现响应式SVG
javascript
svg
.attr("viewBox", `0 0 ${width} ${height}`)
.attr("preserveAspectRatio", "xMidYMid meet")
.style("width", "100%")
.style("height", "auto");javascript
svg
.attr("viewBox", `0 0 ${width} ${height}`)
.attr("preserveAspectRatio", "xMidYMid meet")
.style("width", "100%")
.style("height", "auto");Quality Standards
质量标准
Visual Quality
视觉质量
- Use appropriate chart type for data
- Apply consistent color schemes
- Include clear axis labels and legends
- Provide proper spacing with margin convention
- Use appropriate scale types and ranges
- 根据数据类型选择合适的图表
- 应用一致的配色方案
- 包含清晰的轴标签和图例
- 使用边距约定确保合理间距
- 使用合适的比例尺类型和值域
Interaction Quality
交互质量
- Add meaningful tooltips
- Use smooth transitions (300-500ms duration)
- Provide hover feedback
- Enable keyboard navigation for accessibility
- Implement zoom/pan for detailed exploration
- 添加有意义的工具提示
- 使用平滑过渡动画(300-500ms时长)
- 提供悬停反馈
- 支持键盘导航以提升可访问性
- 实现缩放/平移功能以支持细节探索
Code Quality
代码质量
- Use key functions in data joins
- Handle enter, update, and exit properly
- Clean up previous renders before updates
- Use reusable chart pattern for modularity
- Debounce expensive operations
- 在数据连接中使用键函数
- 正确处理enter、update和exit状态
- 更新前清理之前的渲染内容
- 使用可复用图表模式实现模块化
- 防抖处理高开销操作
Accessibility
可访问性
- Add ARIA labels and descriptions
- Provide keyboard navigation
- Use colorblind-safe palettes
- Include text alternatives for screen readers
- Ensure sufficient color contrast
- 添加ARIA标签和描述
- 支持键盘导航
- 使用色弱友好的调色板
- 为屏幕阅读器提供文本替代方案
- 确保足够的颜色对比度
Helper Resources
辅助资源
Available Scripts
可用脚本
- data-helpers.js: Data loading, parsing, and transformation utilities
- chart-templates.js: Reusable chart templates for common visualizations
See directory for implementations.
scripts/- data-helpers.js:数据加载、解析和转换工具
- chart-templates.js:常见可视化效果的可复用图表模板
具体实现请查看目录。
scripts/Working Examples
示例工程
- line-chart.html: Time series visualization with tooltips
- bar-chart.html: Grouped and stacked bar charts
- network-graph.html: Force-directed network visualization
See directory for complete implementations.
examples/- line-chart.html:带工具提示的时间序列可视化
- bar-chart.html:分组和堆叠柱状图
- network-graph.html:力导向网络可视化
完整实现请查看目录。
examples/Detailed References
详细参考文档
-
D3 Fundamentals: SVG basics, data binding, selections, transitions, events →
references/d3-fundamentals.md -
Scales and Axes: All scale types, axis customization, color palettes →
references/scales-and-axes.md -
Paths and Shapes: Line/area generators, arcs, force simulations →
references/paths-and-shapes.md -
Data Transformation: Loading, parsing, grouping, aggregation, date handling →
references/data-transformation.md -
Chart Types: Detailed guidance on when to use each chart type →
references/chart-types.md -
Advanced Patterns: Reusable charts, performance optimization, responsive design →
references/advanced-patterns.md -
Common Pitfalls: Frequent mistakes and their solutions →
references/common-pitfalls.md -
Integration Patterns: Using D3 with React, Vue, Angular, Svelte →
references/integration-patterns.md
-
D3基础:SVG基础、数据绑定、选择集、过渡动画、事件 →
references/d3-fundamentals.md -
比例尺与轴:所有比例尺类型、轴自定义、配色方案 →
references/scales-and-axes.md -
路径与形状:线/面积生成器、弧形、力模拟 →
references/paths-and-shapes.md -
数据转换:数据加载、解析、分组、聚合、日期处理 →
references/data-transformation.md -
图表类型:详细的图表类型选择指南 →
references/chart-types.md -
高级模式:可复用图表、性能优化、响应式设计 →
references/advanced-patterns.md -
常见陷阱:常见错误及解决方案 →
references/common-pitfalls.md -
集成模式:D3与React、Vue、Angular、Svelte的集成 →
references/integration-patterns.md
本技能全面覆盖了使用D3.js创建专业交互式数据可视化的相关内容。以核心工作流程为起点,针对特定主题参考详细文档,并根据需求自定义示例工程。
Troubleshooting
—
Chart not appearing?
- Check browser console for errors
- Verify data loaded correctly
- Ensure SVG has width and height
- Check scale domains and ranges
Elements in wrong position?
- Verify scale domain matches data range
- Check if y-scale range is inverted:
[height, 0] - Confirm margin transform applied to element
<g> - Check SVG coordinate system (top-left origin)
Transitions not working?
- Ensure duration is reasonable (300-500ms)
- Check if transition applied to selection, not data
- Verify easing function is valid
- Confirm elements exist before transitioning
Poor performance?
- Reduce number of DOM elements (use Canvas if >1,000)
- Aggregate or sample data
- Debounce resize handlers
- Minimize redraws
—
External Resources
—
Official Documentation
—
- D3.js API Reference: https://d3js.org/
- Observable Examples: https://observablehq.com/@d3
—
Learning Resources
—
- "Interactive Data Visualization for the Web" by Scott Murray
- D3 Graph Gallery: https://d3-graph-gallery.com/
- Amelia Wattenberger's D3 Tutorial: https://wattenberger.com/blog/d3
—
Color Tools
—
- ColorBrewer: https://colorbrewer2.org/
- D3 Color Schemes: https://d3js.org/d3-scale-chromatic
—
Inspiration
—
- Observable Trending: https://observablehq.com/trending
- Reddit r/dataisbeautiful: https://reddit.com/r/dataisbeautiful
This skill provides comprehensive coverage of D3.js for creating professional, interactive data visualizations. Use the core workflow as a starting point, refer to the detailed references for specific topics, and customize the examples for your needs.
—