In D3, why Do I need to choose select a dummy object to create something?

Viewed 76

I have a question about creating paths using d3.

I was trying to study a code as below. However, to create a path, the code made an argument svg.selectAll then tie the data set. I was curious about that and manipulate the object to an arbitrary thing, and it still works.

I think I roughly understand the concept of enter(), update() and exit(). However, this case, it challenges me a lot. Why do I have to select dummy object first and make something? and according to the concept of enter() in D3, once enter is executed, the newly assigned object should be assigned for all the path I made but it wasn't The dummy argument selectAll('random') did nothing literally.

The svg part I'm questioning is below.

  svg.selectAll("random")
    .data(allDensity)
    .enter()
    .append("path")
      .attr("transform", function(d){console.log(d3.values(d));return("translate(0," + (yName(d.key)-height) +")" )})
      .datum(function(d){return(d.density)})
      .attr("fill", "#69b3a2")
      .attr("stroke", "#000")
      .attr("stroke-width", 1)
      .attr("d",  d3.line()
          .curve(d3.curveBasis)
          .x(function(d,i) { return x(d[0]); })
          .y(function(d,i) { return y(d[1]); })
      )

entire code:https://codepen.io/jotnajoa/pen/dyogmOz

1 Answers

The strong part of d3 is in modifying objects it previously created. If you don't provide a dummy object, d3 would need an explicit check to see whether it is already created or not. By providing a dummy object, such test isn't needed any more. Also, on a complicated page, the dummy object gives the exact position into the html tree to place the d3 object.

Note that d3 is very open minded, and if you really want you can create the element yourself, especially for examples where the whole page is just one d3 object.

Related