我正在创建一个像这样的序数比例:
var x = d3.scale.ordinal()
.domain(["b1", "b2", "b3", "b4", "b5"])
.rangeBands([0, width], .1);
如果我将此比例与轴一起使用:
var xaxis = d3.svg.axis()
.scale(x)
.orient("bottom");
svg.append("g")
.attr("class", "axis")
.call(xaxis)
.attr("transform", "translate(" + 0 + "," + height + ")");
我发现当轴以 5 个条形图呈现时,它会在最后加上数字。所以我得到:
b1,b2,b3,b4,b5,0,1,2,3,4.
此外,条形图未与刻度对齐。
如何使轴表现得b1,b2,b3,b4,b5
低于 5 条?
这是整个函数:
function barchart_2d_array(width, height, barwidth, data, target_div){
var margin = {top: 20, right: 20, bottom: 30, left: 40},
w = width + margin.left + margin.right,
h = height + margin.top + margin.bottom;
var dataset = data;
values_arr=[];
for(var o in dataset){
values_arr.push(dataset[o]);
}
var x = d3.scale.ordinal()
.rangeBands([0, width], .1);
var y = d3.scale.linear()
.domain([0,d3.max(values_arr)])
.range([height,0]);
var svg = d3.select(target_div)
.append("svg")
.attr("width", w)
.attr("height", h)
.attr("style","border : 1px solid black")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(["b1", "b2", "b3", "b4", "b5"]);
window.x=x;
window.width=width;
svg.selectAll("rect")
.data(values_arr)
.enter()
.append("rect")
.attr("x",function(d,i){
return x(i);
})
.attr("y",function(d,i){
return y(d);
})
.attr("width",barwidth)
.attr("height",function(d,i){
return height - y(d);
});
var yaxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5);
var xaxis = d3.svg.axis()
.scale(x)
.orient("bottom");
svg.append("g")
.attr("class", "axis")
.call(yaxis);
svg.append("g")
.attr("class", "axis")
.call(xaxis)
.attr("transform", "translate(" + 0 + "," + height + ")");
};
这就是我所说的:
<div id="bar_chart">
</div>
<script>
var dataset = { "b1":100, "b2":200, "b3":300, "b4":400, "b5":500 };
a = barchart_2d_array(400,200, 5,dataset,"#bar_chart");
</script>