简体   繁体   English

d3.js:具有两个一维数组的嵌套选择

[英]d3.js: nested selection with two one dimensional arrays

I want to create a table from two one dimensional arrays with d3. 我想用d3从两个一维数组创建一个表。

Let's assume the input arrays are: 我们假设输入数组是:

array1 = ['a','b','c'];
array2 = ['d','e','f'];

I want the table to look like this 我希望桌子看起来像这样

ad  ae  af
bd  be  bf
cd  ce  cf

Should I use a nested selection? 我应该使用嵌套选择吗? Or should I use one call to selectAll().data() , followed by a call to each() ? 或者我应该使用一个调用selectAll().data() ,然后调用each() ( In real life , the operation for each matrix cell won't be as simple as 'a'+'d' , but I don't think this should matter for the answer.) 在现实生活中 ,每个矩阵单元的操作都不会像'a'+'d'那样简单,但我不认为这对答案来说很重要。)

One approach could be to create a new 2D array from your two arrays to make it suitable for the standard nested selection pattern (see: http://bost.ocks.org/mike/nest/ ): 一种方法是从两个数组创建一个新的2D数组,使其适合标准的嵌套选择模式(参见: http//bost.ocks.org/mike/nest/ ):

var arr1 = ['a', 'b', 'c'],
    arr2 = ['d', 'e', 'f'];

// prepare a 2D array
var data = arr1.map(function(v1) {
      return arr2.map(function(v2) {
        return v1 + v2;
      })
    });

d3.select("body").append("table")
  .selectAll("tr")
    .data(data)
  .enter().append("tr")
  .selectAll("td")
    .data(Object)
  .enter().append("td")
    .text(String);

Another approach is to make use of the fact that functions are being passed not only the index i of the element within the group, but also the index j of the group it belongs to: 另一种方法是利用这样一个事实:函数不仅传递给组内元素的索引i,而且还传递它所属组的索引j:

var arr1 = ['a', 'b', 'c'],
    arr2 = ['d', 'e', 'f'];

d3.select("body").append("table")
  .selectAll("tr")
    // arr1 corresponds to the rows
    // bound data is not used in the td cells; only arr1.length is used
    .data(arr1)
  .enter().append("tr")
  .selectAll("td")
    // arr2 corresponds to the columns
    .data(arr2)
  .enter().append("td")
    .text(function(d, i, j) { return arr1[j] + d; }); // d === arr2[i]

A similar approach grabs the bound data from the group using parentNode instead of index j: 类似的方法使用parentNode而不是index j来抓取组中的绑定数据:

var arr1 = ['a', 'b', 'c'],
    arr2 = ['d', 'e', 'f'];

d3.select("body").append("table")
  .selectAll("tr")
    // arr1 corresponds to the rows
    .data(arr1)
  .enter().append("tr")
  .selectAll("td")
    // arr2 corresponds to the columns
    .data(arr2)
  .enter().append("td")
    .text(function(d) { return d3.select(this.parentNode).datum() + d; });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM