Javascript 在文本旁边的表格中内联D3迷你线

Javascript 在文本旁边的表格中内联D3迷你线,javascript,d3.js,Javascript,D3.js,假设有这样一张表: var data = [ ['Orange', 'Orange', [6,3,3,2,5]], ['Apple', 'Red', [6,2,6,5,5]], ['Grape', 'Purple', [9,1,2,3,1]] ] 我希望字符串表示为字符串,但数字数组表示为D3折线图。如果我只关心文本,我可以选择Alltd元素并插入一些文本 var tcells = trows .selectAll("td") .data(functio

假设有这样一张表:

var data = [
    ['Orange', 'Orange', [6,3,3,2,5]],
    ['Apple', 'Red', [6,2,6,5,5]],
    ['Grape', 'Purple', [9,1,2,3,1]]
]
我希望字符串表示为字符串,但数字数组表示为D3折线图。如果我只关心文本,我可以
选择All
td
元素并插入一些文本

var tcells = trows
    .selectAll("td")
    .data(function(d, i) { return d; })
    .enter()
    .append("td")
    .text(function(d, i) { return d; });
第三列是文本,所以我想用图表更新它,或者附加另一列图表。假设
lines
是一个创建折线图的函数,我想调用
lines()
,因为它为每一行传递第三列的数据

trows.selectAll("td")
    .data(function(d) {return d[2]}) // scope out data from 3rd column
    .enter()
    .append("td")
    //.call(lines([3,8,2,5,8,4])); // this works
    .call(lines);                // this doesn't
我的D3知识参差不齐,所以我不清楚数据和选择是如何传递的

以下是完整的代码:

你把这个方法和这个方法搞混了

call
是一种方便的方法,用于调用将选择作为一个参数整体接受的函数
trows.call(lines)
等同于
lines(trows)
,只是它可以是方法链的一部分

每个
用于为选择中的每个元素调用一次函数,将数据和索引作为参数传递

至于为什么
trows.call(行([3,8,2,5,8,4])
“起作用”,那么它只是起作用。您使用硬编码的数据数组调用函数
line
,但该函数不返回任何内容,因此在选择本身上没有要调用的内容。(如果您不理解其中的区别,您可能会这样做。)

您的方法目前也只将折线图附加到主体中,而不将其插入表中。您确认以下代码无效:

// dynamic selection doesn't
this.append("td").append('svg')
    .attr('width', width).attr('height', height)
    .append('path').attr('class','line')
    .datum(data).attr('d', line);
失败的原因有几个:

  • 在调用函数的上下文中,直接调用
    行([3,8,2,5,8,4])
    ,将不会设置
    值,因此将指向窗口对象
  • 即使使用
    each
    方法(设置
    this
    值)调用函数,
    this
    将指向DOM节点,而不是可以调用d3方法的选择
  • 除了在特定情况下,它甚至不会指向DOM节点,因为您是从尚未附加新节点的
    enter()
    选择调用它的
总之,要使事情顺利进行:

  • 在主程序中,在创建新的
    元素后,使用
    每个
    调用
    函数:

    trows.selectAll("td.graph")  
         //use a class so you don't re-select the existing <td> elements
      .data(function(d) {return [d[2]];})
         // the value returned by a data function must always be an array
         // containing data objects for each new element you create -- 
         // you only want one element containing the entire data array, 
         // not individual elements for each number, so wrap it in another array
      .enter()
        .append("td")
        .attr("class", "graph")
        .each(lines); 
    

  • (通过一些其他清理,所以在主程序的中间没有函数定义)

    d3.select(this).append('svg')
            .attr('width', width)
            .attr('height', height)
         .append('path')
            .attr('class','line')
            .datum(data)
            .attr('d', line);