D3访问嵌套数据

时间:2016-03-29 18:13:57

标签: javascript d3.js

我有一些这种格式的嵌套数据:

[{"key":"PFOA",
  "values":[
     {"sampleDate":"2016-0126T05:00:00.000Z",
      "shortName":"PFOA",
      "pfcLevel":0,
      "chemID":1},
     {"sampleDate":"2016-01-19T05:00:00.000Z",
      "shortName":"PFOA",
      "pfcLevel":0,
      "chemID":1},
     {"sampleDate":"2016-01-12T05:00:00.000Z",
      "shortName":"PFOA",
      "pfcLevel":0,
      "chemID":1}
   ],
   "visible":0}
]

我正在尝试使用此数据将圆圈添加到多线图中。如果我直接从数据库使用原始的非嵌套数据,我可以这样做,但这会导致其他问题。如果可能的话,我宁愿为线条和圆圈使用相同的嵌套数据。嵌套函数和圆形代码如下:

var nested_data = d3.nest()
        .key(function(d) { return d.shortName; })
        .entries(data);

var circles = svg.selectAll(".circle")
        .data(nested_data) 
      .enter().append("g")
        .attr("class", "circle");

circles.append("circle")
        .attr("stroke", function(d) { return color(d.key); })
        .attr("fill", "white")
        .attr("cx", function(d, i) { return x(d.values['sampleDate']) })
        .attr("cy", function(d, i) { return y(d.values['pfcLevel']) })
        .attr("r", 2);

我尝试了d.values[sampleDate].data(nested_data.values)之类的不同内容,但我在所有内容上都遇到了未定义的错误。

提前致谢。

1 个答案:

答案 0 :(得分:1)

您正在寻找Nested Selection

var nested_data = d3.nest()
  .key(function(d) {
    return d.shortName;
  })
  .entries(data);

var groups = svg.selectAll(".circle")
  .data(nested_data)
  .enter().append("g")
  .attr("class", "circle");

var circles = groups.selectAll("circle") // start a nested selection
  .data(function(d) {
    return d.values; // tell d3 where the children are
  })
  .enter().append("circle")
  .attr("stroke", function(d) {
    return color(d.shortName);
  })
  .attr("fill", "white")
  .attr("cx", function(d, i) {
    return x(d.sampleDate) // use the fields directly; no reference to "values"
  })
  .attr("cy", function(d, i) {
    return y(d.pfcLevel)
  })
  .attr("r", 2);