我阅读了很多关于在D3条形图上添加标签的文档,但我无法理解.在“svg.selectAll(”text“)”之后,我被卡住了添加什么.
结果将与本例中的相同:http://alignedleft.com/content/03-tutorials/01-d3/130-making-a-bar-chart/18.png
这是代码:
var margin = {top: 20,right: 30,bottom: 50,left: 100},width = 960 - margin.left - margin.right,height = 500 - margin.top - margin.bottom; var x = d3.scale.ordinal() .rangeRoundBands([0,width],.1,1); var y = d3.scale.linear() .range([height,0]); var xAxis = d3.svg.axis() .scale(x) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left") .tickFormat(function (d) { if ((d / 1000000) >= 1) { d = d / 1000000 + " " + "000" + " " + "000"; } return d; }); var svg = d3.select("body").append("svg") .attr("width",width + margin.left + margin.right) .attr("height",height + margin.top + margin.bottom) .append("g") .attr("transform","translate(" + margin.left + "," + margin.top + ")"); d3.csv("./test.csv",function(error,data) { data.forEach(function(d) { d.internaute = +d.internaute; }); x.domain(data.map(function(d) { return d.date; })); y.domain([0,d3.max(data,function(d) { return d.internaute; })]); svg.append("g") .attr("class","x axis") .attr("transform","translate(0," + height + ")") .call(xAxis) .append("text") .attr("x",width / 2) .attr("y",30) .attr("dx",".71em") .style("text-anchor","end") .text("Date"); svg.append("g") .attr("class","y axis") .call(yAxis) .append("text") .attr("transform","rotate(-90)") .attr("y",6) .attr("dy","end") .text("Internautes"); svg.selectAll(".bar") .data(data) .enter().append("rect") .attr("class","bar") .attr("x",function(d) { return x(d.date); }) .attr("width",x.rangeBand()) .attr("y",function(d) { return y(d.internaute); }) .attr("height",function(d) { return height - y(d.internaute);}); svg.selectAll("text") //???? // });
先谢谢你.我希望得到它的保持:)
解决方法
这应该工作!
var yTextPadding = 20; svg.selectAll(".bartext") .data(data) .enter() .append("text") .attr("class","bartext") .attr("text-anchor","middle") .attr("fill","white") .attr("x",function(d,i) { return x(i)+x.rangeBand()/2; }) .attr("y",i) { return height-y(d)+yTextPadding; }) .text(function(d){ return d; });
注意我如何使用类(.bartext)来标识图表标签.