在D3条形图上添加标签 [英] Adding label on a D3 bar chart
本文介绍了在D3条形图上添加标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我阅读了很多关于在D3条形图上添加标签的文档,但我不能弄清楚。我被困在svg.selectAll(text)之后添加什么。
I read a lot of documentation about adding label on a D3 bar chart but i can't figure it out. I am stuck with what to add after the "svg.selectAll("text")".
结果将与此示例中的结果相同: http://alignedleft.com/content/03-tutorials/01-d3/130-making-a-bar-chart/18.png
The result would just be the same as in this example : 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", ".71em")
.style("text-anchor", "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")
//???? //
});
提前感谢。我希望得到它:)
Thank you in advance. I hope to get the hold of it :)
推荐答案
这应该可以工作!
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", function(d,i) {
return height-y(d)+yTextPadding;
})
.text(function(d){
return d;
});
请注意我如何使用类(.bartext)来标识图表标签。
Notice how I use a class (.bartext) to identify the chart labels.
这篇关于在D3条形图上添加标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文