init-barcharts.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. export default (selection, options) => {
  2. // difference bar chart
  3. const resultGroup = selection.append('g').attr('class', 'poll-result');
  4. const differenceGroup = resultGroup.append('g').attr('class', 'poll-result__differences');
  5. const rasterGroup = resultGroup.append('g').attr('class', 'poll-result__raster');
  6. const step = 18;
  7. const yposRectDiff = i => (i * step + options.height / 2.1);
  8. const fontsize = 16;
  9. const distance = (options.width - options.xoffset * 2) / (options.numberOfCols - 1);
  10. // single difference bar chart
  11. // consisting of a rectanlge
  12. differenceGroup.selectAll('rect.diff')
  13. .data(options.data)
  14. .enter()
  15. .append('rect')
  16. .attr('class', 'diff')
  17. .attr('x', options.width / 2)
  18. .attr('y', (d, i) => yposRectDiff(i))
  19. .attr('height', options.barHeight)
  20. .attr('width', 0)
  21. .attr('fill-opacity', 0)
  22. .attr('fill', d => d.color);
  23. // ... and text
  24. differenceGroup.selectAll('text.difftext')
  25. .data(options.data)
  26. .enter()
  27. .append('text')
  28. .attr('class', 'difftext')
  29. .attr('text-anchor', 'middle')
  30. .style('font-size', fontsize)
  31. .attr('x', 0)
  32. .attr('y', (d, i) => (yposRectDiff(i) + fontsize - 2))
  33. .attr('fill', d => d.color)
  34. .attr('fill-opacity', 0)
  35. .text('');
  36. // grid of difference bar charts
  37. for (let x = 0; x < options.numberOfCols; x += 1) {
  38. for (let y = 0; y < 2; y += 1) {
  39. if (!(x === options.numberOfCols - 1 && y === 1)) {
  40. const subgroup = rasterGroup.append('g').attr('class', 'poll-result__raster-item');
  41. subgroup.selectAll('rect.diffgrid')
  42. .data(options.data)
  43. .enter()
  44. .append('rect')
  45. .attr('class', `gridbar diff${x}${y}`)
  46. .attr('x', options.xoffset + x * distance)
  47. .attr('y', (d, i) => (options.yoffset + i * step + options.yoffsetSecRow * y))
  48. .attr('height', options.barHeight)
  49. .attr('width', 0)
  50. .attr('fill-opacity', 1)
  51. .attr('fill', d => d.color);
  52. subgroup.selectAll('text.diffgrid')
  53. .data(options.data)
  54. .enter()
  55. .append('text')
  56. .attr('class', `difftext${x}${y}`)
  57. .attr('text-anchor', 'middle')
  58. .style('font-size', 18)
  59. .attr('x', 0)
  60. .attr('y', (d, i) => (options.yoffset + i * step + options.yoffsetSecRow * y + fontsize - 2))
  61. .attr('fill', d => d.color)
  62. .attr('fill-opacity', 0)
  63. .text('0');
  64. }
  65. }
  66. }
  67. };