d3自定义比例,线性(x),绘制开始和结束

时间:2015-12-30 21:11:33

标签: javascript d3.js

我想从给定的起始位置到具有自定义比例的结束位置绘制一个矩形。 如果数据从0开始并在X结束,则一切都按预期工作。

但是如果数据从X开始并以Y结尾(大于X),由于d3 linear()函数,该值不会在Y处结束(参见FIXME)。 我怎样才能实现这种行为?

说明 数据从250开始,并不以500(250 + 250)结束,而是以1k结束。同样适用于从150开始并且不在500(150 + 350)但在750左右结束的那个。

这是我的代码:

var w = 400;
var h = 175;
var padding = 30;
var groups = [];
groups.push([0, 0, 1000, 30], [0, 0, 6000, 30], [150, 0, 350, 30], [250, 0, 250, 30]);

// Your custom scale:
var scale = [0,125,250,500,1000,2000,4000,6000];
var output = [0,50,100,150,200,250,300,350];
var xScale = d3.scale.linear()
    .domain(scale)
    .range(output);

// The axis uses the above scale and the same domain:
var xAxis = d3.svg.axis()
    .scale(xScale)
    .orient("bottom")
    .tickValues(scale)
    .tickFormat(d3.format("s"));

var svg = d3.select(element)
    .append("svg")
    .attr("width", w)
    .attr("height", h);

//Create X axis
svg.append("g")
    .attr("class", "axis")
    .attr("transform", "translate("+padding+"," + (h - padding) + ")")
    .call(xAxis);


//Drawing data
svg.append("g")
    .attr("id", "groups")
    .selectAll("groups")
    .data(groups)
    .enter()
    .append("g")
    .append("rect")
    .attr("class", "group")
    .attr("x", function(d) {
        return xScale(d[0])+padding;
    })
    .attr("y", function(d, i) {
        return i * d[3];
    })

    //FIXME: something different must be done here.
    .attr("width", function(d) {
        return xScale(d[2]);
    })
    .attr("height", function(d) {
        return d[3];
    });

1 个答案:

答案 0 :(得分:1)

您可以通过从结束位置减去起始位置来计算正确的宽度:

.attr("width", function(d) {
    return xScale(d[0] + d[2]) - xScale(d[0]) - padding;
})