d3.js:具有两个一维数组的嵌套选择 [英] d3.js: nested selection with two one dimensional arrays

查看:127
本文介绍了d3.js:具有两个一维数组的嵌套选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用d3从两个一维数组创建一个表。

I want to create a table from two one dimensional arrays with 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

我应该使用嵌套选择吗?或者我应该使用 selectAll()。data(),然后调用 each()? (在现实生活中,每个矩阵单元的操作不会像'a'+'d',但我不认为这对于答案很重要。)

Should I use a nested selection? Or should I use one call to selectAll().data(), followed by a call to 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.)

推荐答案

一种方法是从两个数组创建一个新的二维数组,使其适合标准的嵌套选择模式(参见: http://bost.ocks.org/mike/nest/ ):

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/):

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);

另一种方法是利用函数不仅传递索引i元素,还包括它所属的组的索引j:

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:

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]

类似的方法从组中捕获绑定数据parentNode而不是索引j:

A similar approach grabs the bound data from the group using parentNode instead of 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; });

这篇关于d3.js:具有两个一维数组的嵌套选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆