如何在d3中创建多个正方形

How can I create multiple squares in d3?

本文关键字:正方形 创建 d3      更新时间:2023-09-26

我有一个交互式页面,我需要使用d3在页面上显示一些正方形,计数如下:1,4,5,16,107,465和1745。我不想多次复制粘贴这个SVG片段。

如何在d3中生成这些正方形?

index.html

<svg width="50" height="50">
    <rect x="0" y="0" width="10" height="10" fill="#c62828">
</svg>

这是符合我从你的问题中理解的最短和"最干净"的d3代码。我已经评论过了,如果有什么不明白的地方请告诉我:

<!DOCTYPE html>
<html>
  <head>
    <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
  </head>
  <body>
    
    <script>
    
    // number of rects
    var data = [1, 4, 5, 16, 107, 465, 1745];
         
    var squareDim = 10, // pixel dimensions of square
        width = 400,
        height = (squareDim * d3.max(data)) + squareDim; // based on the max of my squares, how tall am I going to be
        
    var svg = d3.select('body')
      .append('svg')
      .attr('width', width)
      .attr('height', height); // create my svg node
    
    var row = 0;
    svg.selectAll('rectGroup')
      .data(data)
      .enter()
      .append('g') // for each data point create a group
      .selectAll('rect')
      .data(function(d){
        return d3.range(d); // this creates an array of [1, 2, 3 ... N] where N is a datum in your rect data
      }) // this is a sub selection, it allows you to define a sub dataset
      .enter()
      .append('rect')
      .attr('width', squareDim)
      .attr('height', squareDim)
      .attr('x', function(d,i,j){
        return data.indexOf(j.length) * (squareDim + 2);
      }) // determine the x position
      .attr('y', function(d){
        return d * (squareDim + 2);  // and y
      })
      .style('fill', '#c62828');
      
    </script>
    
  </body>
</html>