SVG:根据价值定位RECT

时间:2016-01-07 23:53:26

标签: javascript d3.js svg charts

我想重新创建此图

<div class="discrete" data-value="1,0,1,0,0,1,0,0,1,1,1,1,1,0,1,0,1,1,1,1"></div>

对于每个1,我想要制作一个上半部分,而0则相反。

function discreteChart(self, dataset) {

  var w = parseInt(d3.select(self).style("width")),
        h = parseInt(d3.select(self).style("height")),

      svg = d3.select(self)
                         .append("svg")
                         .attr("width", w)
                         .attr("height", h),

      yScale = d3.scale
                        .linear()
                        .domain([0, d3.max(dataset)])
                            .range([0, h]);

  svg.selectAll("rect")
        .data(dataset)
    .enter()
    .append("rect")
        .attr('fill', '#363636')
        .attr('rx', '1')
        .attr('ry', '1')
    .attr("x", function(d, i) {
      return i * 3;
    })
    .attr("y", function(d) {
      return h - yScale(d) / 1;
    })
    .attr("width", 1) // width of bar
    .attr("height", function(d) {
      return yScale(d);
    });

}

我的问题是我不完全确定如何做到这一点。我制作了长方形但我无法将它们放置到位。

http://jsfiddle.net/everina/1eec20xe/

2 个答案:

答案 0 :(得分:1)

您可以按照Anko的指示制作线而不是矩形。 以下是如何划线:

  svg.selectAll("line")
    .data(dataset)
    .enter()
    .append("line")
    .attr('stroke', '#363636')
    .attr('x1', function(d, i) {
      return (i + 1) * 10;//xposition of line
    })
    .attr('x2', function(d, i) {
      return (i + 1) * 10;
    })
    .attr('y1', function(d, i) {
      return 10;//starting point of line
    })
    .attr('y2', function(d, i) {
      if (d) {
        return 0; //if 0 then line should be below
      } else {
        return 20;//if non 0 then line should be above
      }
    })

工作示例here

希望这有帮助!

答案 1 :(得分:1)

如果您想使图表可缩放,那么任何高度的位置都是正确的:

svg.selectAll("rect")
    .data(dataset)
.enter()
.append("rect")
    .attr('fill', '#363636')
    .attr('rx', '1')
    .attr('ry', '1')
.attr("x", function(d, i) {
  return i * 3;
})
.attr("y", function(d) {
  return d ? h / 2 : 0;
})
.attr("width", 1) // width of bar
.attr("height", function(d) {
    return h/2;
});