d3-composer

grid and chart components for composing data visualizations with d3

Usage no npm install needed!

<script type="module">
  import d3Composer from 'https://cdn.skypack.dev/d3-composer';
</script>

README

d3-composer

d3-composer consists of two primary concepts: functional chart components and a grid system based on CSS grid.

Functional chart components

A functional chart component approach is used throughout d3-composer and allows complex charts to be composed out of simple, reusable chart components. These match closely to built-in d3 components and can be used with the standard approach of selection.call(...).

function lines(selection, options) {
  // ...
}

function composed(selection, options) {
  lines(selection, options);
  // ...
}

composed(select('...'), { /* ... */ })

// or 

select('...').call(composed, { /* ... */ });

Grid system

d3-composer uses a grid-template approach (see: A Complete Guide to Grid for details) for laying out selections for chart components.

import { template } from 'd3-composer';

const grid = template(`
  "title title" 50
  "y_axis chart" auto
  ". x_axis" 50
  / 50 auto
`, { width: 600, height: 400 });

// For size = { width: 600, height: 400 }:
//
// grid = {
//   title: { x: 0, y: 0, width: 600, height: 50 },
//   y_axis: { x: 0, y: 50, width: 50, height: 300 },
//   chart: { x: 50, y: 50, width: 550, height: 300 },
//   x_axis: { x: 50, y: 350, width: 550, height: 50 }
// }

Usage

For npm / yarn, npm install d3-composer or yarn add d3-composer. Otherwise, you can use unpkg to download the latest release: <script src="https://unpkg.com/d3-composer"></script> and reference d3-composer with the d3c global.

Example

import { select } from 'd3';
import { template, chart, layout, series, line, axisLeft, axisBottom, text, measure } from 'd3-composer';

function lines(selection, options = {}) {
  const { data = [], xScale, yScale  } = options;

  const grid = template(`
    "title title" 50
    "y_axis chart" auto
    ". x_axis" 50
    / 50 auto
  `, measure(selection));

  xScale.range([0, grid.areas.chart.width]);
  yScale.range([grid.areas.chart.height, 0]);

  layout(selection, grid, layers => {
    axisLeft(layers.x_axis(), { scale: xScale });
    axisBottom(layers.y_axis(), { scale: yScale });
    
    line(
      series(layers.chart(), { data }),
      {
        data: series => series.values,
        x: d => xScale(d.x),
        y: d => yScale(d.y)
      }
    );
    
    text(layers.title(), { text: 'Line Chart' });
  });
}

const svg = chart(
  select('#chart'),
  { width: 600, height: 400, responsive: true }
);

lines(svg, { /* ... */ });

Examples

Live examples on observablehq:

API

@d3-composer/grid

@d3-composer/svg

@d3-composer/utils

Development

  • Install: yarn or yarn install (d3-composer uses yarn workspaces)
  • Test: yarn test
  • Build: yarn build
  • Version: npx lerna version VERSION
  • Publish: npx lerna publish from-package --otp ######