Nagendra Somayaji
Nagendra Somayaji

Reputation: 181

D3 bar chart bar text labels not visible properly

I have a stacked bar chart in d3.js For every stacked bar i have corresponding text value showing near stack itself. problem is, some text values displaying are hidden behind bars, where as some are visible over bars. I want all text to visible over my bars. my code looks like,

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');

Upvotes: 2

Views: 1246

Answers (1)

kashesandr
kashesandr

Reputation: 1551

Basically the issue related to z-index. But there is no z-index for SVG, so it can be fixed by reordering elements. Details here With JavaScript, can I change the Z index/layer of an SVG <g> element?

The simplest and fastest way:

To add .reverse() to the dataset.

// 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]; });

The better way

To add different containers for bars and labels and put them in the right order in the DOM.

Try it http://jsfiddle.net/kashesandr/z90aywdj/

Upvotes: 2

Related Questions