我正在尝试使用多个2数组来绑定svg圆的数据,但不知道如何绑定

I am trying to use multiple 2 arrays for binding data for svg circles but cannot figure out how

本文关键字:绑定 数据 不知道 何绑定 svg 数组      更新时间:2023-09-26

假设我有两个数组:

    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格式可以更简单,但如果我用数组完成这项工作会更好。

提前谢谢。

只需获取所处的索引,并从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
  })