Menu

Annotated column

Since we want an ordinal x-axis and Layer Cake defaults to a linear scale, pass in a custom scale to xScale with a few formatting options. Set the y-scale to always start at 0 so you don't show misleading differences between groups.

import LayerCake from 'layercake';
import { scaleBand } from 'd3-scale';
import groups from './data/groups.js';
import Column from './components/Column.html';
import AxisX from './components/AxisXScaleBand.html';
import AxisY from './components/AxisY.html';
import Annotations from './components/Annotations.html';
import Arrows from './components/Arrows.html';
import DefArrowhead from './components/DefArrowhead.html';

const annotations = [
  {
    text: 'Example text...',
    top: '18%',
    left: '30%',
    arrows: [{
      clockwise: false, // true or false, defaults to true
      source: {
        anchor: 'left-bottom', // can be `{left, middle, right},{top-middle-bottom}`
        dx: -2,
        dy: -7
      },
      target: {
        x: '28%',
        y: '75%'
      }
    },
    {
      source: {
        anchor: 'right-bottom',
        dy: -7,
        dx: 5
      },
      target: {
        x: '68%',
        y: '48%'
      }
    }]
  }
];

const myCake = new LayerCake({
  padding: { top: 0, right: 0, bottom: 20, left: 20 },
  x: 'year',
  y: 'value',
  xScale: scaleBand().paddingInner([0.02]).round(true),
  xDomain: ['1979', '1980', '1981', '1982', '1983'],
  yDomain: [0, null],
  data: groups,
  target: document.getElementById('my-chart')
})
  .svgLayers([
    { component: AxisX, opts: { gridlines: false } },
    { component: AxisY, opts: { gridlines: false } },
    { component: Column, opts: {} }
  ])
  .htmlLayers([
    { component: Annotations, opts: { annotations } }
  ])
  .svgLayers([
    { component: Arrows, opts: { annotations } }
  ], { defs: DefArrowhead });

myCake.render();