【问题标题】:How to append multiple rectangles in D3?如何在 D3 中附加多个矩形?
【发布时间】:2019-03-20 03:21:45
【问题描述】:

我想知道是否可以为每个数据点附加多个矩形。 在我的示例中,有三个数据点。 对于每个我尝试创建 2 个矩形。 最后必须有6个矩形。 3个红色,3个蓝色。 IMAGE

根据this的回答,我尝试了以下解决方案:

var svg = d3.select("body").append("svg");

      svg.selectAll("rect")
      .data([10,60,120])
      .enter()
      .append("g")
      .append("rect")
      .attr("width", 20)
      .attr("height", 20)
      .attr("x", 20)
      .attr("y", function(d) {return d})
      .attr("fill",  "red")

      .selectAll("rect")
      .data(function(d) { return d3.range(d); })
      .enter()
      .append("rect")
      .attr("width", 20)
      .attr("height", 20)
      .attr("x", 60)
      .attr("y", function(d) {return d})
      .attr("fill",  "blue");

不幸的是,蓝色矩形是在红色矩形内创建的。知道如何实现这一目标吗? 这是EXAMPLE

【问题讨论】:

    标签: javascript d3.js append rectangles


    【解决方案1】:

    您成功地创建了额外的矩形,但不幸的是它们都嵌套在前三个矩形内。如果您的浏览器上有 Web 开发者扩展程序,请选择其中一个矩形,然后查看源代码以查看。

    如果要附加矩形,而不是将它们嵌套在原始矩形内,则需要将两个矩形都附加到 g 节点。当您绑定数据并添加 g 节点时,将这些节点分配给一个变量:

    var svg = d3.select("body").append("svg");
    
    var nodes = svg.selectAll(".rect")
      .data([10,60,120])
      .enter()
      .append("g")
      .classed('rect', true)
    

    然后您可以将两个矩形附加到g 节点:

    // red rectangles
    nodes.append("rect")
      .attr("width", 20)
      .attr("height", 20)
      .attr("x", 20)
      .attr("y", function(d) {return d})
      .attr("fill",  "red")
    
    // blue ones
    nodes.append("rect")
      .attr("width", 20)
      .attr("height", 20)
      .attr("x", 120)
      .attr("y", function(d) {return d})
      .attr("fill",  "blue")
    

    请注意,如果您这样做:

    var nodes = svg.selectAll("rect")
      .data([10,60,120])
      .enter()
      .append("g")
      .append("rect")
      .attr("width", 20)
      .attr("height", 20)
      .attr("x", 20)
      .attr("y", function(d) {return d})
      .attr("fill",  "red")
    

    nodes 将引用 rect 元素,因为它们是最后添加的,任何附加到 nodes 的内容都将添加到 inside rect 元素中。

    还请注意,您只需将数据绑定一次,即绑定到g 元素;它被那些g 元素的所有子节点自动继承。

    这是完整的示例:

    var svg = d3.select("body").append("svg");
    
    var g = svg.selectAll(".rect")
      .data([10,60,120])
      .enter()
      .append("g")
      .classed('rect', true)
    
    g.append("rect")
      .attr("width", 20)
      .attr("height", 20)
      .attr("x", 20)
      .attr("y", function(d) {return d})
      .attr("fill",  "red")
    
    g.append("rect")
      .attr("width", 20)
      .attr("height", 20)
      .attr("x", 120)
      .attr("y", function(d) {return d})
      .attr("fill",  "blue")
    <script src="https://d3js.org/d3.v5.js"></script>

    【讨论】:

    • 非常感谢您提供这个令人难以置信的答案。这是理解 d3.js 的一大步。
    猜你喜欢
    • 2014-01-05
    • 2019-12-14
    • 2021-04-01
    • 2016-07-22
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多