我想将每个条形的值对齐,但我不能将标签文本的中间部分与矩形的中间对齐。
function createBarChart(panel, cs_data) {
var data = [
{
"label":"1998",
"value":"0.2301495972382"
},
{
"label":"1999",
"value":"0.12531328320802"
},
....
{
"label":"2011",
"value":"0.4907688712316"
}];
var margin = {top: 20, right: 30, bottom: 30, left: 40},
width = parseInt(panel.getWidth()) - margin.left - margin.right,
height = parseInt(panel.getHeight()) - margin.top - margin.bottom;
var max = d3.max(data, function(d) {
return d.value;
});
var x = d3.scale.ordinal()
.domain([1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011])
.rangeBands([0, width], .1);
var y = d3.scale.linear()
.domain([0, max])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
d3.select(".chart").selectAll("*").remove();
var chart = d3.select(".chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
chart.append("g")
.attr("class", "y axis")
.call(yAxis);
chart.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.label); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.attr("width", x.rangeBand());
chart.selectAll('.text')
.data(data)
.enter().append("svg:text")
.attr("x", function(d) { return x(d.label) + x.rangeBand()/2; })
.attr("y", function(d) { return y(d.value); })
.attr("dy", ".35em")
.text(function(d) { return d.value.toFixed(2); });
}
答案 0 :(得分:1)
您需要考虑<text>
:
chart.selectAll('.text')
.data(data)
.enter().append("text")
.text(function(d) { return parseFloat(d.value).toFixed(2); })
.attr("x", function(d) {
return x(d.label) + x.rangeBand()/2 - this.getComputedTextLength() / 2;
})
.attr("y", function(d) { return y(d.value) - 10; })
.attr("dy", ".35em");
示例here。