Arash Howaida
Arash Howaida

Reputation: 2617

D3 Modify Path's y

I have some user events that append different paths to an svg. What I would like is for each subsequent path to be drawn below the previous path (+ some padding). I would assume this would be done by style.top or .attr('y', my_value). However neither worked for me. And if nothing is done to address this, then the paths will be drawn on top of eachother, which is bad. Should be straight forward, but for added clarity, let me provide the crucial code:

  graphGroup.append("path")
      .datum(data)
      .attr("fill", "none")
      .attr("d", line);

I suppose I could programtically create n number of gs, (i.e. graphGroup2 = svg.append('g').attr('transform', 'translate(' + my_transformation +')') and so forth, but I think there should be an easier way. Maybe a dynamic y:

//var count = graphGroup....???
//count could be a way to count the existing number of paths in the g graphGroup


  graphGroup.append("path")
      .datum(data)
      .attr("fill", "none")
      .attr('y', count*200)
      .attr("d", line);

Obviously, I don't know how to make my dynamic approach work. If you think it could work, you can build off it, or feel free to scrap it in favor of another way.

Upvotes: 1

Views: 51

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

A SVG <path> element has no y attribute. You'll have to use translate to set the vertical position of those paths. You don't have to create additional < g> elements, though: all the paths can be in the same group.

Here is a demo, where I'm increasing a count variable inside a loop to translate the paths down:

var svg = d3.select("body")
  .append("svg")
  .attr("width", 300)
  .attr("height", 300);

var d = "M10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80";

var count = 0;
(function loop() {
  if (count++ > 5) return;
  setTimeout(function() {
    svg.append("path")
      .attr("stroke", "black")
      .attr("d", d)
      .attr("fill", "none")
      .attr("transform", "translate(0," + count * 20 + ")")
    loop();
  }, 1000);
})();
<script src="https://d3js.org/d3.v4.min.js"></script>

Upvotes: 1

Related Questions