import * as d3 from 'd3'; // d3js module for module04: sort poll bar chart export default () => { // defaults const options = { width: 475, height: 500, radius: 10 }; // start const poll = selection => { const svg = selection.select('svg'); const xScale = d3.scaleLinear().domain([ 0, 100 ]).range([ 0, options.width ]); const distance = (options.width - options.xoffset * 2) / (options.numberOfCols - 1); const step = 18; const duration = 2000; // get rectangle x coordinate const getRectXval = (d, i) => { let index = i; if (i >= options.numberOfCols) index -= options.numberOfCols; const xBase = options.xoffset + distance * index; return d > 0 ? xBase : xBase - xScale(Math.abs(d)); }; // get text x coordinate const getTextXval = (d, i) => { let index = i; if (i >= options.numberOfCols) index -= options.numberOfCols; let xBase = options.xoffset + distance * index; if (d > 0) { xBase = xBase + xScale(d) + 7; } else { xBase = xBase - xScale(Math.abs(d)) - 6; } return xBase; }; // get rectangle y coordinate const getRectYval = (i, x, y) => { let xBase = x; if (y > 0) xBase += options.numberOfCols; let yBase = options.yoffset + step * xBase; if (i >= options.numberOfCols) yBase += options.yoffsetSecRow; return yBase; }; // get text y coordinate const getTextYval = (i, x, y) => { let xBase = x; if (y > 0) xBase += options.numberOfCols; let yBase = options.yoffset + step * xBase + 14; if (i >= options.numberOfCols) yBase += options.yoffsetSecRow; return yBase; }; // move bars and texts for (let x = 0; x < options.numberOfCols; x += 1) { for (let y = 0; y < 2; y += 1) { // Move the bars svg.selectAll(`.diff${x}${y}`) .transition() .duration(duration) .attr('x', (d, i) => getRectXval(d, i)) .attr('y', (d, i) => getRectYval(i, x, y)); // Move the text svg.selectAll(`.difftext${x}${y}`) .transition() .duration(duration) .attr('x', (d, i) => getTextXval(d, i)) .attr('y', (d, i) => getTextYval(i, x, y)); } } window.setTimeout(() => (options.setData({ continue: true })), duration); }; // "setter" poll.options = input => { Object.assign(options, input); return poll; }; return poll; };