根据数据属性更改d3.js符号大小

时间:2018-09-23 16:37:31

标签: javascript d3.js

我正在尝试根据数据集中的属性“ WinsNoms”的值来缩放符号的大小。该图表将被渲染,但不会根据“ winsNoms”进行缩放。谁能帮我我在哪里错了?

var sizeExtent = d3.extent(data, function(d) { return d.WinsNoms });
var sizeScale = d3.scale.linear()
                .domain(sizeExtent)
                .range([5,15]);

var symbolTypesx = {
    "cross": d3.svg.symbol().type("cross").size(function(d) { return sizeScale(d.WinsNoms);}),
    "circle": d3.svg.symbol().type("circle").size(function(d) { return sizeScale(d.WinsNoms);})
};

svg2.selectAll("path")
    .data(data)
    .enter().append("path")
    .attr("class", "dot")
    // position it, can't use x/y on path, so translate it
    .attr("transform", function(d) { 
        return "translate("+xScale(d.imdbRating)+","+yScale(d.imdbVotes)+")"; 
    })
   .attr("d", function(d,i){
        if (d.IsGoodRating === 0)
        { // circle if bar === 0
            return symbolTypesx.circle();
        }
        else
        {
            return symbolTypesx.cross();
        }
    })
    // fill based on goo and foo
   .style("fill", function(d,i){
        if (d.IsGoodRating === 0)
                return "red";
            else
                return "blue";
    });

1 个答案:

答案 0 :(得分:2)

调用它时,您需要将基准传递到symbol函数中:

return symbolTypesx.circle(d);

运行代码:

<!DOCTYPE html>
<html>

<head>
  <script data-require="d3@3.5.17" data-semver="3.5.17" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
</head>

<body>
  <script>
  
    var svg2 = d3.select("body")
      .append("svg")
      .attr("width", 500)
      .attr("height", 500);
  
    var data = [{
      WinsNoms: Math.random(),
      GoodRathing: Math.random() > 0.5 ? 1 : 0
    }, {
      WinsNoms: Math.random(),
      GoodRathing: Math.random() > 0.5 ? 1 : 0
    }, {
      WinsNoms: Math.random(),
      GoodRathing: Math.random() > 0.5 ? 1 : 0
    }, {
      WinsNoms: Math.random(),
      GoodRathing: Math.random() > 0.5 ? 1 : 0
    }, {
      WinsNoms: Math.random(),
      GoodRathing: Math.random() > 0.5 ? 1 : 0
    }];

    var sizeExtent = d3.extent(data, function(d) {
      return d.WinsNoms
    });
    var sizeScale = d3.scale.linear()
      .domain(sizeExtent)
      .range([5, 250]);

    var symbolTypesx = {
      "cross": d3.svg.symbol().type("cross").size(function(d) {
        return sizeScale(d.WinsNoms);
      }),
      "circle": d3.svg.symbol().type("circle").size(function(d) {
        return sizeScale(d.WinsNoms);
      })
    };

    svg2.selectAll("path")
      .data(data)
      .enter()
      .append("path")
      .attr("class", "dot")
      .attr("transform", function(d,i) {
        return "translate(" + ((i * 20) + 10) + "," + ((i * 20) + 10) + ")";
      })
      .attr("d", function(d, i) {
        if (d.IsGoodRating === 0) { // circle if bar === 0
          return symbolTypesx.circle(d);
        } else {
          return symbolTypesx.cross(d);
        }
      });;
  </script>
</body>

</html>