zelda26
zelda26

Reputation: 489

D3 conditional styling of edges

I need to set line color, thickness, and dashed/not dashed based on if a value is 0 or 1. Using d3.v5.min.js.

This works for the color. How can I also set the thickness and dash attributes? Can I return them in the same function?

var path = svg.append("g")
  .selectAll("path")
  .data(links)
  .enter()
  .append("path")
    .attr("class", function(d) { return "link " + d.type; })//;
    .style("stroke", function(d) { 
      if (d.value == 1 ) { return ('green'); } 
      else { return 'black'; } 
    } )
    .attr('stroke-width', function(d) {  //THIS PART DOES NOT WORK
      if (d.value == 1 ) { return ('solid'); } 
      else { return 'dashed'; } 
    } );

//DO I ALSO NEED ANOTHER IF STATEMENT FOR LINE THICKNESS?

Upvotes: 0

Views: 4829

Answers (1)

lemming
lemming

Reputation: 1873

stroke-width is a valid attribute for an SVG path element, but it expects a numerical value in pixels, e.g.

.attr('stroke-width', function(d) {
  if(d.value === 1) {
    return 2;
  } else {
    return 5;
  }
})

The attribute to define a dashed line is stroke-dasharray, where you specify the lengths of the dash and the length of the space inbetween the dashes using 2 numbers, e.g.

.attr('stroke-dasharray', function(d) {
  if(d.value === 1) {
    return '5, 5';
  } else {
    // for solid line
    return null;
  }
})

There's good documentation on all this on the MDN website.

The following is an example of a path with all of these values set declaratively (without code).

<svg width="300" height="150">
    <path d="M 10 75 Q 50 10 100 75 T 190 75" stroke="black"
    stroke-width="2" stroke-dasharray="5,2" fill="none" />
</svg>

Upvotes: 3

Related Questions