casillas
casillas

Reputation: 16793

Create Lines in SVG

In the following code, I am adding three lines on the top of each other with a small gap from each other. However, I would like to know there is another way to make the code more modular?

I mean, instead of copy and pasting the legend.append("line") for each of them, i guess there might be better way to make into one rather than three.

enter image description here

    var legendData = [{ color: "white", text: "MyData" }];
        var legends = svg.selectAll("g legends").data(legendData);
        var legendBox = legends.enter()
             .append("g")


       legendBox.append("line")
          .attr("x1", 200)
          .attr("x2", 215)
          .attr("y1", 24)
          .attr("y2", 24)
          .attr("stroke", "steelblue")
          .attr("stroke-width", "2")


        legendBox.append("line")
          .attr("x1", 200)
          .attr("x2", 215)
          .attr("y1", 12)
          .attr("y2", 12)
          .attr("stroke", "green")
          .attr("stroke-width", "2")


        legendBox.append("line")
          .attr("x1", 200)
          .attr("x2", 215)
          .attr("y1", 0)
          .attr("y2", 0)
          .attr("stroke", "red")
          .attr("stroke-width", "2")

Upvotes: 0

Views: 113

Answers (2)

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

The D3 way to do this is to define the coordinates as data and then select and match accordingly:

var data = [{x1: 200, x2: 215, y1: 24, y2: 24, color: "steelblue"},
            {x1: 200, x2: 215, y1: 12, y2: 12, color: "green"},
            {x1: 200, x2: 215, y1: 0, y2: 0, color: "red"}];

legendBox.selectAll("line").data(data)
  .enter().append("line")
  .attr("x1", function(d) { return d.x1; })
  .attr("x2", function(d) { return d.x2; })
  .attr("y1", function(d) { return d.y1; })
  .attr("y2", function(d) { return d.y2; })
  .attr("stroke", function(d) { return d.color; })
  .attr("stroke-width", "2");

Upvotes: 2

David162795
David162795

Reputation: 1866

If these lines were connected, you could have used polyline or polygon instead. But for this case, there is no other way (at least no serious one), then to define each line separately. You can, however, generate them like this:

colors = ["steelblue", "green", "red"];
for(i=0;i<3;i++)
{
   legendBox.append("line")
      .attr("x1", 200)
      .attr("x2", 215)
      .attr("y1", i*12)
      .attr("y2", i*12)
      .attr("stroke", colors[i])
      .attr("stroke-width", "2")
}

Upvotes: 2

Related Questions