Menu

Histogram (variable bins)

40 bins
import LayerCake from 'layercake';
import { histogram, extent } from 'd3-array';
import unemployment from './data/unemployment.js';
import Column from './components/ColumnLinear.html';
import AxisX from './components/AxisX.html';
import AxisY from './components/AxisY.html';
import thresholds from './modules/thresholds.js';

const doughmain = extent(unemployment);
const hist = histogram()
  .domain(doughmain)
  .thresholds(thresholds(doughmain, 40));

const bins = hist(unemployment);

const myCake = new LayerCake({
  padding: { top: 10, right: 5, bottom: 20, left: 20 },
  x: ['x0', 'x1'],
  y: 'length',
  xNice: true,
  yDomain: [0, null],
  data: bins,
  target: document.getElementById('my-chart')
})
  .svgLayers([
    { component: AxisX, opts: { gridlines: false, baseline: true, snapTicks: true } },
    { component: AxisY, opts: { gridlines: false, ticks: 3 } },
    { component: Column, opts: { fill: '#fff', stroke: '#000', 'stroke-width': 1 } }
  ]);

myCake.render();

const inputContainer = document.querySelector('.input-container[data-which="histogram"]');
const counterContainer = inputContainer.querySelector('.counter-container');

inputContainer.querySelector('input').addEventListener('input', e => {
  const binCount = e.target.value;
  counterContainer.innerHTML = binCount + ' bins';
  hist.thresholds(thresholds(doughmain, binCount));
  const bins = hist(unemployment);

  myCake.set({ data: bins });
});