我有一个这样的堆叠条形,性别在堆叠条形图上显示为不同颜色的堆叠:
我想向每个堆栈中添加文本,以便我可以知道每种关系的确切男性和女性人数。下面是CSV格式的数据部分:
Year,Relations,Female,Male
2002,Family/Relative,0,0
2002,Friend,0,0
2002,Intimate Partner,0,0
2002,Other,0,0
2002,Unknown,1116,0
2003,Family/Relative,0,0
2003,Friend,0,0
2003,Intimate Partner,0,0
2003,Other,0,0
2003,Unknown,364,15
2004,Family/Relative,0,0
2004,Friend,0,0
2004,Intimate Partner,0,0
2004,Other,0,0
2004,Unknown,250,0
以下是我认为添加文本的代码应添加到的代码:
function update(input, speed) {
var data = csv.filter(f => f.Year == input)
data.forEach(function(d) {
d.total = d3.sum(keys, k => +d[k])
return d
})
yScale.domain([0, d3.max(data, d => d3.sum(keys, k => +d[k]))]).nice();
svg.selectAll(".y-axis").transition().duration(speed)
.call(d3.axisLeft(yScale).ticks(null, "s"))
data.sort(d3.select("#sort").property("checked")
? (a, b) => b.total - a.total
: (a, b) => Relations.indexOf(a.Relations) - Relations.indexOf(b.Relations))
xScale.domain(data.map(d => d.Relations));
svg.selectAll(".x-axis").transition().duration(speed)
.call(d3.axisBottom(xScale).tickSizeOuter(0))
var group = svg.selectAll("g.layer")
.data(d3.stack().keys(keys)(data), d => d.key)
group.exit().remove()
group.enter().append("g")
.classed("layer", true)
.attr("fill", d => z(d.key));
var bars = svg.selectAll("g.layer").selectAll("rect")
.data(d => d, e => e.data.Relations);
bars.exit().remove()
bars.enter().append("rect")
.attr("width", xScale.bandwidth())
.merge(bars)
.transition().duration(speed)
.attr("x", d => xScale(d.data.Relations))
.attr("y", d => yScale(d[1]))
.attr("height", d => yScale(d[0]) - yScale(d[1]))
下面是活动代码的链接: