我在jsfiddle中创建了一个列条形图。但问题是我无法将X轴标签与特定条形图(直接在条形图下)相关联。你能帮助我吗 ?我的代码如下。
function drawColumnChart() {
var dataArray_o, maxNum_f, canvas_o, canvas_top;
dataArray_o = [
{name: "PS 1", value: "3000" },
{name: "PS 2", value: "1000" },
{name: "PS 3", value: "5000" },
{name: "PS 4", value: "2000" }
];
var values = [];
var names = [];
for (var index_i = 0; index_i < dataArray_o.length; index_i++) {
values.push(dataArray_o[index_i].value);
names.push(dataArray_o[index_i].name);
}
maxNum_f = Math.max.apply(null, values);
var margin = {top: 20, right: 20, bottom: 30, left: 40}
var w = 500 - margin.left - margin.right, h = 500 - margin.top - margin.bottom;
var yScale = d3.scale.linear().domain([0, maxNum_f]).rangeRound([0, h]);
var yScale1 = d3.scale.linear().domain([0, maxNum_f]).rangeRound([h, 0]);
var xScale = d3.scale.ordinal().rangeRoundBands([0, w], 0) ;
var yAxis = d3.svg.axis().scale(yScale1).ticks(5).orient("left");
var xAxis = d3.svg.axis().scale(xScale).orient("bottom").tickFormat(function(v){
console.log(v);
return v;
});
canvas_top= d3.select("#ColumnChart").append("svg").attr("height", h + margin.top + margin.bottom).attr("width", w + margin.left + margin.right);
canvas_o = canvas_top.append("g").attr("transform", "translate(50, 0)");
var rects = canvas_o.selectAll("rect");
var totalRect = h / 20 ;
var dArr = [];
for (var i = 0; i < totalRect; i++) {
dArr.push(i);
}
var bars2 = rects.data(dArr).enter().append("rect").attr("height", function(d){
return 20;
}).attr("width", w).attr("x", function(d, i){
return 0;
}).attr("y", function(d, i){
return i *20;
}).
attr("fill", function(d, i) {
if (i % 2 == 0) {
return "grey";
} else {
return "white";
}
}).attr("opacity", "0.08");
rects.data(dataArray_o).enter().append("rect").attr("class", "bar").attr("width", 15).attr("height", function(d) {
return yScale(d.value);
}).attr("x", function(d, i) {
return i*30 + 5;
}).
attr("y", function(d, i) {
return h - yScale(d.value);
}).attr("fill", "#330066");
canvas_top.selectAll("text").data(dataArray_o).enter().append("text").text(function(d) {
return d.value;
}).attr("text-anchor", "middle")
.attr("x", function(d, i) {
return i*30 + 10;
})
.attr("y", function(d) {
return h - yScale(d.value);
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
xScale.domain(names);
canvas_top.append("g").attr("transform", "translate(50, 5)").call(yAxis);
canvas_top.append("g").
attr("transform", "translate(50," + h +")").
call(xAxis);
}
有什么想法吗?