# 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. ## Install Save as a script file and run: ## Quick Use ```bash npm i d3 ``` ```ts 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"); ``` ## Intro 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). - **Repo**: https://github.com/d3/d3 - **Stars**: 112K+ - **License**: ISC ## 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 - Docs: https://d3js.org - GitHub: https://github.com/d3/d3 - License: ISC --- Source: https://tokrepo.com/en/workflows/ee953940-3577-11f1-9bc6-00163e2b0d79 Author: Script Depot