Menu

Cleveland dot plot

You could create this kind of plot by reshaping your data into rows of containing name, value and group and plot it kind of like a scatter plot. But here's another way that keeps the data in its current form and takes advantage of Layer Cake's accessor shorthand. In main.js, we simply specify the names of the keys in each row that we want to plot and in the layer component, we call $xGet(row) and it maps our row into an array of pixel values.

import LayerCake from 'layercake';
import { scaleBand } from 'd3-scale';
import fruit from './data/fruitOrdinal.js';
import ClevelandDotPlot from './components/ClevelandDotPlot.html';
import AxisX from './components/AxisX.html';
import AxisY from './components/AxisYScaleBand.html';

const colors = ['#f0c', '#00bbff', '#00e047', '#ffdd57'];

const myCake = new LayerCake({
  padding: { right: 10, bottom: 20, left: 30 },
  x: ['apples', 'bananas', 'cherries', 'dates'],
  y: 'year',
  yScale: scaleBand().paddingInner([0.05]).round(true),
  yDomain: ['2016', '2017', '2018', '2019'],
  xDomain: [0, null],
  xPadding: [10, 0],
  data: fruit,
  target: document.getElementById('my-chart')
})
  .svgLayers([
    { component: AxisX, opts: {} },
    { component: AxisY, opts: { gridlines: false } },
    { component: ClevelandDotPlot, opts: { colors } }
  ]);

myCake.render();