Scripts2026年4月11日·1 分钟阅读

D3.js — Bring Data to Life with SVG, Canvas & HTML

D3 is the grandparent of data visualization on the web — a low-level toolkit for binding data to DOM, applying data-driven transformations, and building any chart imaginable. Powers the New York Times, Observable, and thousands of dashboards.

SC
Script Depot · Community
快速使用

先拿来用,再决定要不要深挖

这里应该同时让用户和 Agent 知道第一步该复制什么、安装什么、落到哪里。

npm i d3
import * as d3 from "d3";

const data = [10, 20, 30, 40, 50];

const svg = d3.select("body")
  .append("svg")
  .attr("width", 400)
  .attr("height", 200);

svg.selectAll("rect")
  .data(data)
  .enter()
  .append("rect")
  .attr("x", (_, i) => i * 60)
  .attr("y", (d) => 200 - d * 3)
  .attr("width", 50)
  .attr("height", (d) => d * 3)
  .attr("fill", "steelblue");
介绍

D3 (Data-Driven Documents) is a JavaScript library for visualizing data with SVG, Canvas, and HTML. Created by Mike Bostock in 2011, D3 is the foundation of most famous data journalism visualizations (NYT, FT, The Guardian, Pudding).

What D3 Does

  • Selections — jQuery-like DOM manipulation
  • Scales — map data to visual properties (linear, log, time, ordinal, band)
  • Axes — auto-generate axis ticks and labels
  • Shapes — pie, arc, area, line, stack, hierarchy generators
  • Layouts — force, tree, pack, treemap, Sankey, chord
  • Transitions — smooth animated updates
  • Geo — projections, topojson, maps
  • Data loading — CSV, TSV, JSON parsers

Architecture

D3 is modular — each package (d3-scale, d3-shape, d3-selection) is independently publishable. Core pattern: bind data → select DOM → enter/update/exit pattern → apply attributes. Unlike chart libraries, D3 gives you primitives to build any visualization.

Self-Hosting

Client library only. Ships in your frontend bundle.

Key Features

  • Data-driven DOM manipulation
  • 30+ scale types
  • Comprehensive shape generators
  • Force-directed graphs
  • Geographic projections
  • Smooth transitions
  • Canvas + SVG + HTML targets
  • Modular packages (install only what you need)

Comparison

Tool Level Learning Curve Customization
D3 Low-level primitives Steep Unlimited
Chart.js High-level charts Easy Limited
ECharts High-level charts Easy Themes
Observable Plot D3-based higher level Easy Good
Visx D3 + React Medium Unlimited

常见问题 FAQ

Q: D3 vs Chart.js? A: Chart.js 是成品图表库(折线、柱状、饼图),5分钟出图。D3 是建造积木,能画任何可视化但要写很多代码。

Q: 和 React 冲突吗? A: D3 操作 DOM 会和 React 虚拟 DOM 打架。推荐用 D3 算布局/比例尺,用 React 渲染 SVG。Visx 就是这个思路。

Q: 学习曲线陡? A: 非常陡。先学 selection、scale、axis 三大核心,再按需学 shape/layout/geo。观察者模式是关键。

来源与致谢 Sources

讨论

登录后参与讨论。
还没有评论,来写第一条吧。

相关资产