Skip to content

D3.js Visualizations

Testing D3.js interactive visualizations in markdown.

D3.js Interactive Visualizations

This document demonstrates how to embed interactive D3.js visualizations in markdown using the ::d3_ directive.

Example: Sales Data Bar Chart

Here's a simple bar chart showing monthly sales data:

Loading visualization...

Monthly Sales Data

Usage

The ::d3 directive follows this syntax:

::d3[Title]{data="/assets/viz/data/sales.json" script="/assets/viz/scripts/bar-chart.js" width="800" height="400"}

Parameters

  • data: Path to the JSON data file (relative to /assets/viz/)
  • script: Path to the JavaScript visualization script (relative to /assets/viz/)
  • width: Width of the visualization (default: "100%")
  • height: Height of the visualization (default: "400")
  • title: Optional title displayed above the visualization
  • className: Optional CSS class name

Script Context

Your visualization script receives the following variables:

  • d3: The D3.js library
  • data: The loaded JSON data
  • svg: A D3 selection of the SVG element
  • container: The container DOM element
  • width: The width in pixels
  • height: The height in pixels

Example Script Structure

// Set up scales
const xScale = d3.scaleBand()
  .domain(data.map(d => d.month))
  .range([0, width])
  .padding(0.1);
 
const yScale = d3.scaleLinear()
  .domain([0, d3.max(data, d => d.sales)])
  .range([height, 0]);
 
// Create bars
svg.selectAll('rect')
  .data(data)
  .enter()
  .append('rect')
  .attr('x', d => xScale(d.month))
  .attr('y', d => yScale(d.sales))
  .attr('width', xScale.bandwidth())
  .attr('height', d => height - yScale(d.sales))
  .attr('fill', 'steelblue');

Tags

devjavascriptd3visualizationdata-viz