2

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

1 Answers1

2

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/

Community
  • 1
  • 1
kashesandr
  • 1,521
  • 28
  • 35
  • I have tried it.. Its working in many labels, one or two still as before, not completely visible – Nagendra Somayaji Jun 17 '15 at 04:22
  • Okay, basically the problem in z-index as I wrote before (see comments here http://stackoverflow.com/questions/482115/with-javascript-can-i-change-the-z-index-layer-of-an-svg-g-element/482147#482147). So, here we have to change the order of elements to support what you need. – kashesandr Jun 17 '15 at 09:04
  • I'll try to reorder them today, but not sure will have enough time. Try it by yourself. – kashesandr Jun 17 '15 at 09:04