【问题标题】:I am trying to use multiple 2 arrays for binding data for svg circles but cannot figure out how我正在尝试使用多个 2 个数组来绑定 svg 圆圈的数据,但无法弄清楚如何
【发布时间】:2016-09-09 09:14:08
【问题描述】:

假设我有 2 个数组:

    var x_axis_values = [0,1,2,3];

    var y_axis_values = [2,3,4,5];

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

                                     .attr("width", 200)

                                     .attr("height", 200);

var circles = svgContainer.selectAll("circle")

                        .data(x_axis_values)
                        .enter()
                        .append("circle");


var circleAttributes = circles

                        .attr("cx",function(d) {return d;})

这里我无法为“cy”绑定数据,因为我使用的数组是 x_axis_values。如何在此处绑定来自 y_axis_values 数组的数据?我知道使用 JSON 格式可能会更简单,但如果我使用数组来完成它会更好。

提前致谢。

【问题讨论】:

    标签: javascript arrays d3.js svg


    【解决方案1】:

    只需获取您所在的索引并从y_axis_values 数组中返回相应的值:

    var x_axis_values = [0, 1, 2, 3];
    
    var y_axis_values = [2, 3, 4, 5];
    
    var svgContainer = d3.select("body").append("svg")
      .attr("width", 200)
      .attr("height", 200);
    
    var circles = svgContainer.selectAll("circle")
    
    .data(x_axis_values)
      .enter()
      .append("circle");
    
    
    var circleAttributes = circles
      .attr("cx", function(d) {
        return d;
      })
      .attr("cx", function(d, i) { //add i here to get current index
        return y_axis_values[i]; //gets current index of x_axis_values and  gets the corresponding y_axis_values value
      })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 2023-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多