poll-sortbars.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import * as d3 from 'd3';
  2. // d3js module for module04: sort poll bar chart
  3. export default () => {
  4. // defaults
  5. const options = {
  6. width: 475,
  7. height: 500,
  8. radius: 10
  9. };
  10. // start
  11. const poll = selection => {
  12. const svg = selection.select('svg');
  13. const xScale = d3.scaleLinear().domain([ 0, 100 ]).range([ 0, options.width ]);
  14. const distance = (options.width - options.xoffset * 2) / (options.numberOfCols - 1);
  15. const step = 18;
  16. const duration = 2000;
  17. // get rectangle x coordinate
  18. const getRectXval = (d, i) => {
  19. let index = i;
  20. if (i >= options.numberOfCols) index -= options.numberOfCols;
  21. const xBase = options.xoffset + distance * index;
  22. return d > 0 ? xBase : xBase - xScale(Math.abs(d));
  23. };
  24. // get text x coordinate
  25. const getTextXval = (d, i) => {
  26. let index = i;
  27. if (i >= options.numberOfCols) index -= options.numberOfCols;
  28. let xBase = options.xoffset + distance * index;
  29. if (d > 0) {
  30. xBase = xBase + xScale(d) + 7;
  31. } else {
  32. xBase = xBase - xScale(Math.abs(d)) - 6;
  33. }
  34. return xBase;
  35. };
  36. // get rectangle y coordinate
  37. const getRectYval = (i, x, y) => {
  38. let xBase = x;
  39. if (y > 0) xBase += options.numberOfCols;
  40. let yBase = options.yoffset + step * xBase;
  41. if (i >= options.numberOfCols) yBase += options.yoffsetSecRow;
  42. return yBase;
  43. };
  44. // get text y coordinate
  45. const getTextYval = (i, x, y) => {
  46. let xBase = x;
  47. if (y > 0) xBase += options.numberOfCols;
  48. let yBase = options.yoffset + step * xBase + 14;
  49. if (i >= options.numberOfCols) yBase += options.yoffsetSecRow;
  50. return yBase;
  51. };
  52. // move bars and texts
  53. for (let x = 0; x < options.numberOfCols; x += 1) {
  54. for (let y = 0; y < 2; y += 1) {
  55. // Move the bars
  56. svg.selectAll(`.diff${x}${y}`)
  57. .transition()
  58. .duration(duration)
  59. .attr('x', (d, i) => getRectXval(d, i))
  60. .attr('y', (d, i) => getRectYval(i, x, y));
  61. // Move the text
  62. svg.selectAll(`.difftext${x}${y}`)
  63. .transition()
  64. .duration(duration)
  65. .attr('x', (d, i) => getTextXval(d, i))
  66. .attr('y', (d, i) => getTextYval(i, x, y));
  67. }
  68. }
  69. window.setTimeout(() => (options.setData({ continue: true })), duration);
  70. };
  71. // "setter"
  72. poll.options = input => {
  73. Object.assign(options, input);
  74. return poll;
  75. };
  76. return poll;
  77. };