Menu

Stacked column

import { default as LayerCake, flatten, uniques } from 'layercake';
import { stack } from 'd3-shape';
import { scaleBand } from 'd3-scale';
import fruit from './data/fruitOrdinal.js';
import ColumnStacked from './components/ColumnStacked.html';
import AxisX from './components/AxisXScaleBand.html';
import AxisY from './components/AxisY.html';

const seriesNames = Object.keys(fruit[0]).filter(d => d !== 'year');

const stackData = stack()
  .keys(seriesNames);

const series = stackData(fruit);

function formatYTick (d) {
  if (d > 999) {
    return Math.round(d / 1000) + 'k';
  }
  return d;
}

const colors = ['#00e047', '#7ceb68', '#b7f486', '#ecfda5'];

const myCake = new LayerCake({
  padding: { top: 0, right: 0, bottom: 20, left: 20 },
  x: d => d.data.year,
  y: [0, 1],
  xScale: scaleBand().paddingInner([0.02]).round(true),
  xDomain: uniques(fruit, 'year'),
  flatData: flatten(series),
  data: series,
  target: document.getElementById('my-chart'),
  seriesNames_: seriesNames
})
  .svgLayers([
    { component: AxisX, opts: { gridlines: false } },
    { component: AxisY, opts: { gridlines: false, formatTick: formatYTick } },
    { component: ColumnStacked, opts: { colors } }
  ]);

myCake.render();