使用d3.js

时间:2016-10-06 15:46:24

标签: javascript css d3.js

我觉得我在这里效率低下。我试图从数组创建一个图例,似乎我写的太多了。有人能告诉我它是否可以优化?

http://jsbin.com/foqesivice/edit?js,console,output

var data = [
    {name: "AnotherLong"},
    {name: "BigData"},
    {name: "What"},
    {name: "Something"},
    {name: "Smalls"}
];

var margin = {top: 10, right: 10, bottom: 10, left: 10};

var color = d3.scale.category20c();

var svg = d3.select("body").append("svg")
  .attr("width", 400 - margin.left - margin.right)
  .attr("height", 1000 - margin.top - margin.bottom)

var g = svg.selectAll(".row")
  .data(data)
  .enter().append("svg:g")

var rectangles = g.selectAll(".cell")
  .data(data)
  .enter().append("svg:rect")
  .attr("width", 19)
  .attr("height", 19)
  .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; })
  .style("fill", function(d, i){return color(i);})

var text = g.selectAll(".text")
  .data(data)
  .enter().append("svg:text")
  .attr("x", 24)
  .attr("y", 9)
  .attr("dy", ".35em")
  .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; })
  .text(function(d){return d.name;})

编辑:

困扰我的另一件事。看起来我的造型因为某种原因都是大胆的。我没有定义任何样式。这是默认行为吗?

2 个答案:

答案 0 :(得分:2)

首先,将所有测量值和值移到文件的顶部并引用它们(这只会使事情更具可读性)

var legend_row_height = 50;

您不需要创建g元素。只需使用x,y属性而不是翻译来定位矩形和文本:

.attr("y", function(d,i){return legend_row_height * i;})

将您的样式转换为CSS。通过在对象上设置类最容易实现:

.classed("squares", 1)

然后添加CSS:

.squares {
   stroke: white;
}

答案 1 :(得分:1)

@ MatthewWilcoxson的答案很好,但这里有更多d3具体的重写。从本质上讲,不要对数据进行双重绑定,保留g,对其进行绑定,定位并向其添加recttext



<!DOCTYPE html>
<html>

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

<body>
  <script>
    var data = [{
      name: "AnotherLong"
    }, {
      name: "BigData"
    }, {
      name: "What"
    }, {
      name: "Something"
    }, {
      name: "Smalls"
    }];

    var margin = {
      top: 10,
      right: 10,
      bottom: 10,
      left: 10
    };

    var color = d3.scale.category20c(),
      cellDim = 19;

    var svg = d3.select("body").append("svg")
      .attr("width", 400 - margin.left - margin.right)
      .attr("height", 1000 - margin.top - margin.bottom);

    var g = svg.selectAll(".row")
      .data(data)
      .enter().append("svg:g")
      .attr("transform", function(d, i) {
        return "translate(" + (0) + "," + ((cellDim + 1) * i) + ")"
      });

    g.append("svg:rect")
      .attr("width", cellDim)
      .attr("height", cellDim)
      .style("fill", function(d, i) {
        return color(i);
      });

    g.append("text")
      .attr("dy", "1em")
      .attr("dx", cellDim + 2)
      .text(function(d) {
        return d.name;
      });
      
  </script>
</body>

</html>
&#13;
&#13;
&#13;