简体   繁体   English

D3访问嵌套数据

[英]D3 access nested data

I have some nested data in this format: 我有一些这种格式的嵌套数据:

[{"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}
]

I'm trying to use this data to add circles to a multi-line graph. 我正在尝试使用此数据将圆添加到多线图中。 I can do this if I use the raw, non-nested data directly from the database, but that is causing other issues. 如果我直接从数据库中使用原始的,非嵌套的数据,则可以执行此操作,但这会导致其他问题。 I'd rather use the same nested data for the lines and the circles if possible. 如果可能的话,我宁愿对线和圆使用相同的嵌套数据。 The nest function and the circle code is below: 嵌套函数和圆形代码如下:

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

I've tried different things like d.values[sampleDate] or .data(nested_data.values) but I am getting undefined errors on all of them. 我已经尝试过类似d.values[sampleDate].data(nested_data.values)但是我都遇到了未定义的错误。

Thanks in advance. 提前致谢。

You are looking for a 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM