[英]d3 custom scale, linear(x), draw start and end
我想使用自定義比例從給定的開始位置到結束位置繪制一個矩形。 如果數據從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];
});
您可以通過從結束位置減去開始位置來計算正確的寬度:
.attr("width", function(d) {
return xScale(d[0] + d[2]) - xScale(d[0]) - padding;
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.