簡體   English   中英

使用D3 data()。enter()

[英]Using D3 data().enter()

以下玩具問題說明了我的問題。 一張藏寶圖說,我有一系列的“位置”。 陣列中的每個項目(例如怪物或寶藏)都可以存在於地圖上的多個位置。 例如

locations = [
  {name:'treasure', color: 'blue', coords:[[100,100], [200,300]]},
  {name:'monsters', color: 'red', coords:[[100,150], [220,420], [50,50]]}
]

現在,我想使用D3繪制這些圖形。 壞/天真的方法(有效- 在這里查看小提琴 )看起來像這樣:

for location in locations
  for coords in location.coords
    svg.append('circle')
      .attr('cx', coords[0])
      .attr('cy', coords[1])
      .attr('r', 8)
      .style('fill', location.color)
      .datum(location)

但是,當我修改數據的內容時,我不想每次都運行此幼稚的代碼。 看來使用data()和enter()是做到這一點的“正確”方法,但我無法弄清楚它如何與子坐標一起工作。 例如

svg.selectAll('circle').data(locations).enter().append('circle')
  .attr('cx', (d) -> d.coords[0][0])
  .attr('cy', (d) -> d.coords[0][1])
  .attr('r', 8)
  .style('fill', (d) -> d.color)

這很好用,但是如您所見,我只在每個位置都打印所有位置的第一坐標。 我懷疑這樣做的唯一方法是展平我的數據數組,因此總共有5個條目-3個怪物和2個寶藏物品。

只是想知道是否有一種方法可以使用D3更好地處理此問題。

為此,您需要嵌套選擇 這個想法是,您可以附加多個元素,而不是每個數據項附加單個元素。 在代碼中,它看起來像這樣:

// append a `g` element for each data item to hold the circles
var groups = svg.selectAll("g.circle").data(locations)
   .enter().append("g").attr("class", "circle");

// now select all the circles in each group and append the new ones
groups.selectAll("circle")
   // the d in this function references a single data item in locations
   .data(function(d) { return d.coords; })
   .enter().append("circle")
   .attr("cx", function(d) { return d[0]; })
   .attr("cy", function(d) { return d[1]; });

它對更新和退出選擇的作用相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM