Search code examples
d3.jsscalestroke

d3js scaling stroke width


I am currently drawing some arrows and would like them to have different/scaling stroke-widths (some being fatter than others) I am currently using this code but the stroke width just won't change. If I hard code a value like 5 it does change to that. I am using exactly the same scaling in another code but there I am scaling the heights of bars (no problems there).

Here is a fiddle of what I'm working with: https://fiddle.jshell.net/42jdw2Lt/ I would like to use the values in series that I marked as "num" to scale my strokewidth with.

    <!DOCTYPE html>
<meta charset="utf-8">

<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js">
</script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>

<script>

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

var strwi = d3.scaleLinear()
          .domain([100, 400])
          .range([7,35])

var group = svg.append("g")

var series = [
             [{"x": 360, "y": 250, "num": 100}, {"x": 520, "y": 400, "num": 
             100}, {"x": 630, "y": 300, "num": 100}],
             [{"x": 71, "y": 45, "num": 200}, {"x": 32, "y": 39, "num": 
             200}, {"x": 43, "y": 70, "num": 200}],
             [{"x": 100, "y": 300, "num": 300}, {"x": 200, "y": 200, "num": 
             300}, {"x": 300, "y": 200, "num": 300}], [{"x": 101, "y": 202, 
             "num": 400}, {"x": 102, "y": 204, "num": 400}, {"x": 103, "y": 
             215, "num": 400}]
  ];

  var line = d3.line()
  .curve(d3.curveBasis)
  .x(function(d) { return d.x; })
  .y(function(d) { return d.y; });

   svg.append("svg:defs").append("svg:marker")
    .attr("id", "triangle")
    .attr("refX", 0)
    .attr("refY", 5)
    .attr("markerWidth", 14)
    .attr("markerHeight", 14)
    .attr("viewBox", "0 0 20 10")
    .attr("orient", "auto")
    .append("path")
    .attr("d", "M 0,0 L 10,5 L 0,10 z")
    .style("fill", "black");

    group.selectAll(".line")
    .data(series)
    .enter().append("path")
    .attr("class", "line")
    .attr("stroke-width", function(d) {return strwi(d); })
    .attr("stroke", "black")
    .attr("fill", "none")
    .attr("d", line)
    .attr("marker-end", "url(#triangle)");

   </script>

Solution

  • I just made a couple of changes to the code:

    • I set stroke-width and some other attibutes as styles
    • I used the first element of a series, and its num property, to compute the width

    The code now looks like this, and has different thicknesses for each series

    group.selectAll(".line")
        .data(series)
      .enter().append("path")
        .attr("class", "line")
        .style("stroke-width", function(d) {return strwi(d[0].num); })
        .style("stroke", "black")
      .style("fill", "none")
        .attr("d", line)
        .attr("marker-end", "url(#triangle)");