8
我正在d3.js中創建一個條形圖,其中的順序x軸的刻度應該用文本標記圖表。任何人都可以解釋序數標度如何將x滴答「映射」到相應的酒吧位置?具體來說,如果我想用條形圖中的相應條指定具有文本值數組的x刻度標籤。在D3.js中使用序號比例創建文本標記的x軸
目前我設置域爲以下幾點:
var labels = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t"];
var xScale = d3.scale.ordinal()
.domain(labels)
然而,1-19值在文本標籤後顯示。
在本小提琴看到:
http://jsfiddle.net/chartguy/FbqjD/
美聯社小提琴源代碼:
//Width and height
var margin = {top: 20, right: 20, bottom: 30, left: 40};
var width = 600 - margin.left - margin.right;
var height= 500-margin.top -margin.bottom;
var w = width;
var h = height;
var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];
var labels = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t"];
var xScale = d3.scale.ordinal()
.domain(labels)
.rangeRoundBands([margin.left, width], 0.05);
var xAxis = d3.svg.axis().scale(xScale).orient("bottom");
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset)])
.range([h,0]);
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
//Create bars
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return yScale(d);
})
.attr("width", xScale.rangeBand())
.attr("height", function(d) {
return h - yScale(d);
})
.attr("fill", function(d) {
return "rgb(0, 0, 0)";
});
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + 0 + ")")
.call(xAxis);
//Create labels
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("x", function(d, i) {
return xScale(i) + xScale.rangeBand()/2;
})
.attr("y", function(d) {
return h - yScale(d) + 14;
});
那麼,如何將值標籤對併入d3中的單個對象而不是鏈接它標記爲一個對象並賦值給一個對象。我非常感謝你的迴應,但是我想要多走一步,並且知道幕後到底發生了什麼,所以我不只是巧合編程。 – arete
這是因爲你正在用一組數據顯式定義域,然後當你執行'.attr(「x」,function(d,i){return xScale(i);})'時,將另一個集合傳遞給它。來自API參考的[相關行](https://github.com/mbostock/d3/wiki/Ordinal-Scales#wiki-ordinal_domain)表示:「如果域被明確設置,那麼傳遞給該比例的值不是明確的部分域將被添加。「爲此,您可能會注意到,在您的原始代碼調用x軸之前,rects將導致您的顯式數組被調用。 – nsonnad