我在 d3.js 中有一个堆积条形图 对于每个堆叠条形图,我都有相应的文本值显示在堆叠本身附近。 问题是,一些显示的文本值隐藏在条形后面,而有些则在条形上方可见。我希望所有文本都在我的栏上可见。我的代码看起来像,
bar.append("text")
.attr("x", function (d) { return x(d.x); })
.attr("y", function (d) { return y(d.y0 + d.y); })
.attr("dy", ".35em")
.attr('style', 'font-size:13px')
.text(function (d) { if (d.y != 0) { return "$" + d.y; } })
.style('fill', 'black');
最佳答案
基本上是与 z-index 有关的问题。但SVG没有z-index,因此可以通过重新排序元素来修复。详情请点击With JavaScript, can I change the Z index/layer of an SVG <g> element?
最简单、最快的方法:
将.reverse()
添加到数据集。
// Create groups for each series, rects for each segment
var groups = svg.selectAll("g.cost")
.data(dataset.reverse())
.enter().append("g")
.attr("class", "cost")
.style("fill", function(d, i) { return colors[i]; });
更好的方法
为栏和标签添加不同的容器,并将它们按正确的顺序放置在 DOM 中。
关于javascript - D3 条形图条形文本标签不正确可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30863996/