app.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* global d3 */
  2. // D3 convention: define margin as an object called margin with these props:
  3. let margin = {
  4. top: 10,
  5. right: 20,
  6. bottom: 60,
  7. left: 40
  8. };
  9. let width = 425 - margin.left - margin.right;
  10. let height = 625 - margin.top - margin.bottom;
  11. let svg = d3.select('.chart')
  12. .append('svg')
  13. // Match the size of the chart-containing <div>.
  14. .attr('width', width + margin.left + margin.right)
  15. .attr('height', height + margin.top + margin.bottom)
  16. .append('g')
  17. .attr('transform', () => `translate(${margin.left},${margin.top})`);
  18. // Everything below this line no longer needs to care about margins.
  19. // At this point, the "svg" variable actually contains the <g> selection.
  20. svg.append('rect')
  21. .attr('width', width)
  22. .attr('height', height)
  23. .style('fill', 'lightblue')
  24. .style('stroke', 'green');
  25. let yScale = d3.scaleLinear()
  26. .domain([0, 100])
  27. // reversed because SVG coordinates are top to bottom.
  28. .range([height, 0]);
  29. let yAxis = d3.axisLeft(yScale)
  30. // For 2nd ticks() param:
  31. // - '%' assumes a [0,1] domain
  32. // - 's' uses human-readable sizes
  33. // - '.2s' gives 2 digits after decimal separator
  34. // The value is a suggestion, in this case we get 6, not 5.
  35. // .ticks(5);
  36. // Can use explicit tick positions:
  37. // .tickValues([8, 19, 43, 77])
  38. svg.call(yAxis);
  39. let xScale = d3.scaleTime()
  40. .domain([new Date(2016, 0, 1, 6), new Date(2016, 0, 1, 9)])
  41. .range([0, width])
  42. let xAxis = d3.axisBottom(xScale)
  43. .ticks(5)
  44. // .tickSize(20)
  45. .tickSizeInner(10)
  46. .tickSizeOuter(20)
  47. .tickPadding(15)
  48. // Not every 45 minutes, but every 45 minutes after the hour, plus the hour.
  49. //.ticks(d3.timeMinute.every(45))
  50. ;
  51. // This would appear at the top (but drawn for a bottom position, ticks down).
  52. // svg.call(xAxis);
  53. // So we put it in an additional <g> below the graph.
  54. svg.append('g')
  55. .attr('transform', `translate(0, ${height})`)
  56. .call(xAxis);