【问题标题】:How to use a value in d3 data key function?如何在 d3 数据键功能中使用值?
【发布时间】:2019-02-27 16:53:50
【问题描述】:

这个问题在 d3 v5 上。

对我来说,D3 似乎无法识别关键功能的价值。例如

// first create 5 elements
var data = d3.range(0,5);
var g = d3.select('svg')
  .append('g').selectAll("text")
  .data(data, d=>d+"_a");  // append value "a"

console.log(`new ${g.enter().size()} update ${g.size()} exit ${g.exit().size()}`);

// do some dummy stuff
g.enter()
  .append("text")
  .attr("id", d=>d+"_a");

var data = [1,2];
var g = d3.selectAll('text')
  .data(data, d=>d+"_b");  // append a different value "b"

// shouldn't this show: new 2 update 0 exit 5?
console.log(`new ${g.enter().size()} update ${g.size()} exit ${g.exit().size()}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width=100 height=100> </svg>

是否可以在定义键功能时添加“值”?还是只能来自数据?

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    关键功能仅用于比较。它还将键函数中引用的数据与基于键函数绑定到元素的数据进行比较。 您不能在键函数中添加值。

    另请参阅: https://github.com/d3/d3-selection#selection_data

    官方文档说:

    可以指定一个键功能来控制分配给哪个数据 哪个元素,通过计算a来替换默认的join-by-index 每个数据和元素的字符串标识符。这个关键功能是 按顺序对每个选定元素进行评估,通过 当前基准 (d)、当前索引 (i) 和当前组 (nodes), this 作为当前 DOM 元素 (nodes[i]);返回的 string 是元素的键。然后还评估关键功能 对于 data 中的每个新数据,通过当前数据 (d), 当前索引 (i) 和组的新数据,以此作为组的 父 DOM 元素;返回的字符串是数据的键。基准 对于给定的键,分配给具有匹配键的元素。如果 多个元素具有相同的键,重复的元素被放置 进入退出选择;如果多个数据具有相同的键,则 重复的数据被放入输入选择中。

    看看你的例子:

    var data = d3.range(0,5);
    var g = d3.select('svg')
      .append('g').selectAll("text")
      .data(data, d=>d+"_a");
    // the g selection is joined with [0,1,2,3,4]
    // the key function doesn't find a match with elements (there is none anyway)
    // so g.enter() contains a placeholder for 5 elements
    // which will be joined with 0,1,2,3,4 respectively
    
    // do some dummy stuff
    g.enter()
      .append("text")
      .attr("id", d=>d+"_a");
    
    var data = [1,2];
    var g = d3.selectAll('text')
      .data(data, d=>d+"_b");  
    // now the 5 elements are joined with the Array [1,2]
    // The key function looks for data which concatenated with "_b" matches
    // with the data bound to the elements.
    // So it essentially compares the data from the array with the data bound to the elements. 
    // A simpler way to write the key function is
    // .data(data, d => d)
    // which is a common d3.js join pattern.
    // Thus, the second and third <text> element match
    // this condition and end up in the update selection 
    

    这里也有一个有用的 SO 答案: d3.js data join shows strange result

    【讨论】:

      猜你喜欢
      • 2020-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-25
      • 2019-02-08
      • 1970-01-01
      • 2019-07-18
      相关资源
      最近更新 更多