D3.js

D3.js (Data-Driven Documents) is a powerful JavaScript library used to create dynamic, interactive, and visually appealing data visualizations in web applications. Unlike traditional charting libraries, D3.js provides complete control over the visualization process, allowing developers to bind data to HTML, SVG, and CSS elements.

What Is D3.js?

D3.js is not just a charting library—it’s a framework for creating custom visualizations. By leveraging web standards like HTML, SVG, and CSS, it enables developers to craft highly customized and performant visualizations.

Key Features of D3.js

  • Data Binding: Bind data directly to DOM elements.
  • Custom Visualizations: Create any visualization, from bar charts to advanced maps.
  • Flexibility: Use D3.js with any web technology.
  • Rich Animations: Add transitions and interactivity to charts.

Getting Started

Installation

Using CDN
Include D3.js in your HTML file:

<script src="https://d3js.org/d3.v7.min.js"></script>

Using npm
Install D3.js in your project:

npm install d3

Basic Example: A Simple Bar Chart

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>D3.js Bar Chart</title>
  <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
  <svg width="500" height="300"></svg>
  <script>
    const data = [10, 20, 30, 40, 50];
    const svg = d3.select('svg');
    const width = svg.attr('width');
    const height = svg.attr('height');
    const barWidth = width / data.length;

    svg.selectAll('rect')
      .data(data)
      .enter()
      .append('rect')
      .attr('x', (d, i) => i * barWidth)
      .attr('y', d => height - d * 5)
      .attr('width', barWidth - 2)
      .attr('height', d => d * 5)
      .attr('fill', 'teal');
  </script>
</body>
</html>

Common Visualizations

1. Line Chart

<svg width="500" height="300"></svg>
<script>
  const data = [10, 20, 30, 40, 50];
  const svg = d3.select('svg');
  const width = svg.attr('width');
  const height = svg.attr('height');

  const xScale = d3.scaleLinear().domain([0, data.length - 1]).range([0, width]);
  const yScale = d3.scaleLinear().domain([0, d3.max(data)]).range([height, 0]);

  const line = d3.line()
    .x((d, i) => xScale(i))
    .y(d => yScale(d));

  svg.append('path')
    .datum(data)
    .attr('d', line)
    .attr('fill', 'none')
    .attr('stroke', 'steelblue')
    .attr('stroke-width', 2);
</script>

2. Scatter Plot

<svg width="500" height="300"></svg>
<script>
  const data = [
    { x: 10, y: 20 },
    { x: 30, y: 40 },
    { x: 50, y: 60 },
    { x: 70, y: 80 }
  ];

  const svg = d3.select('svg');
  const width = svg.attr('width');
  const height = svg.attr('height');

  svg.selectAll('circle')
    .data(data)
    .enter()
    .append('circle')
    .attr('cx', d => d.x)
    .attr('cy', d => height - d.y)
    .attr('r', 5)
    .attr('fill', 'orange');
</script>

3. Pie Chart

<svg width="300" height="300"></svg>
<script>
  const data = [10, 20, 30, 40];
  const width = 300;
  const height = 300;
  const radius = Math.min(width, height) / 2;

  const svg = d3.select('svg')
    .attr('width', width)
    .attr('height', height)
    .append('g')
    .attr('transform', `translate(${width / 2}, ${height / 2})`);

  const pie = d3.pie();
  const arc = d3.arc().innerRadius(0).outerRadius(radius);

  const colors = d3.scaleOrdinal(d3.schemeCategory10);

  svg.selectAll('path')
    .data(pie(data))
    .enter()
    .append('path')
    .attr('d', arc)
    .attr('fill', (d, i) => colors(i));
</script>

Advanced Features

Transitions and Animations

Add transitions to make visualizations more dynamic:

d3.selectAll('rect')
  .transition()
  .duration(1000)
  .attr('fill', 'blue');

Event Handling

Handle user interactions like hover or click:

svg.selectAll('circle')
  .on('mouseover', function () {
    d3.select(this).attr('fill', 'red');
  })
  .on('mouseout', function () {
    d3.select(this).attr('fill', 'orange');
  });

Tooltips

Add tooltips to display additional information:

svg.selectAll('circle')
  .on('mouseover', (event, d) => {
    d3.select('body')
      .append('div')
      .attr('class', 'tooltip')
      .style('left', `${event.pageX}px`)
      .style('top', `${event.pageY}px`)
      .text(`Value: ${d.y}`);
  });

Leave a Comment