Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 (v4): update pattern multiple elements in group

Tags:

d3.js

I have a chart with multiple g elements that contain a circle and a text element.

I use the following code:

  var nodes = [{"oe": 1, "name": 'test'},{"oe": 1, "name": 'test2'},{"oe": 0, "name": 'test3'}]

  //join 
  var nodeGroups = d3.select('g.maingroup').selectAll('g.nodegroup').data(nodes);

  //enter
  var nodeGroupsEnter = nodeGroups.enter().append('g').attr("class", "nodegroup");      
  nodeGroupsEnter.append("circle");              
  nodeGroupsEnter.append("text");

  //update
  nodeGroups.select("circle")
    .attr("r", 4)
    .attr("class", function(d) {
      return ((d.oe) ? " oe" : "");
    });

  nodeGroups.select("text")
    .text(function (d) {
      return d.name;
    })
    .attr("text-anchor", "top")
    .attr("y", 10)
    .attr("dy", -15);    

  //exit
  nodeGroups.exit().remove();   

All the g elements are drawn, however both the circle and text elements are empty, the attributes do not seem to be added properly during the update fase. Any ideas on why this is?

note: I am using v4 of d3

like image 453
Christian-G Avatar asked Apr 18 '17 11:04

Christian-G


1 Answers

Actually this seems to working (just added and svg element and centered the nodes)

Edit

For v4 you need to merge selections, see below:

var nodes = [{
  "oe": 1,
  "name": 'test'
}, {
  "oe": 1,
  "name": 'test2'
}, {
  "oe": 0,
  "name": 'test3'
}]

//join 
var nodeGroups = d3.select('svg').append('g')
 .attr('transform', 'translate(50, 50)')
 .selectAll('g.nodegroup').data(nodes);

//enter
var nodeGroupsEnter = nodeGroups.enter().append('g').attr("class", "nodegroup");

nodeGroupsEnter.append("circle");
nodeGroupsEnter.append("text");

//update
nodeGroups.merge(nodeGroupsEnter).select("circle")
  .attr("r", 4)
  .attr("class", function(d) {
    return ((d.oe) ? " oe" : "");
  });

nodeGroups.merge(nodeGroupsEnter).select("text")
  .text(function(d) {
    return d.name;
  })
  .attr("text-anchor", "top")
  .attr("y", 10)
  .attr("dy", -15);

//exit
nodeGroups.exit().remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.8.0/d3.min.js"></script>
<svg width="100" height="100"></svg>
like image 77
thedude Avatar answered Sep 28 '22 02:09

thedude