image.png

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>testD3-3-drawingDivBar</title>
  6. <style>
  7. .box {
  8. border: 1px solid #ddd;
  9. }
  10. .bar {
  11. display: inline-block;
  12. width: 24px;
  13. background-color: teal;
  14. }
  15. </style>
  16. <script src="https://cdn.bootcdn.net/ajax/libs/d3/7.3.0/d3.js"></script>
  17. </head>
  18. <body>
  19. <div class="box"></div>
  20. <script>
  21. const dataset = [3, 5, 10, 15, 20, 25];
  22. const gutter = 16;
  23. d3.select(".box")
  24. .selectAll('.bar')
  25. .data(dataset)
  26. .enter()
  27. .append("div")
  28. .attr("class", "bar")
  29. .style("height", (d) => `${d * 10}px`)
  30. .style('margin-right', `${gutter}px`)
  31. </script>
  32. </body>
  33. </html>

柱状图

image.png

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>d3</title>
  6. <style>
  7. * {
  8. box-sizing: border-box;
  9. }
  10. body {
  11. width: 960px;
  12. margin: 32px auto;
  13. }
  14. .bar {
  15. width: 500px;
  16. height: 265px;
  17. background: rgba(0, 0, 0, 0.2);
  18. position: relative;
  19. }
  20. p {
  21. position: absolute;
  22. margin: 0;
  23. padding-right: 8px;
  24. line-height: 24px;
  25. text-align: right;
  26. color: #fff;
  27. font-size: 12px;
  28. }
  29. </style>
  30. <script src="https://cdn.bootcdn.net/ajax/libs/d3/7.3.0/d3.js"></script>
  31. </head>
  32. <body>
  33. <div class="bar"></div>
  34. <script>
  35. const dataset = [100, 200, 250, 300, 350, 450, 500];
  36. const [width, height] = [16, 24]
  37. const root = d3.select('.bar')
  38. .selectAll('p')
  39. .data(dataset)
  40. .enter().append('p')
  41. .style('left', 0)
  42. .style('top', (d, i) => {
  43. console.log('d', d, i)
  44. return `${i * (width + height)}px`;
  45. })
  46. .style('width', (d, i) => {
  47. return `${d}px`;
  48. })
  49. .style('height', `${height}px`)
  50. .style('background', '#90f')
  51. .text(d => d);
  52. </script>
  53. </body>
  54. </html>