Menu

Stacked bar

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

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

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

const series = stackData(fruit);

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

const colors = ['#00bbff', '#8bcef6', '#c4e2ed', '#f7f6e3'];

const myCake = new LayerCake({
  padding: { top: 0, right: 0, bottom: 20, left: 30 },
  y: d => d.data.year,
  x: [0, 1],
  yScale: scaleBand().paddingInner([0.05]).round(true),
  yDomain: ['2016', '2017', '2018', '2019'],
  flatData: flatten(series),
  data: series,
  target: document.getElementById('my-chart'),
  seriesNames_: seriesNames
})
  .svgLayers([
    { component: AxisX, opts: { formatTick: formatXTick, baseline: true, snapTicks: true } },
    { component: AxisY, opts: { gridlines: false } },
    { component: BarStacked, opts: { colors } }
  ]);

myCake.render();