SteveSong
SteveSong

Reputation: 311

Labels do not display with D3 v4 bar chart

I am struggling to add vertical labels to the individual bars in a D3 Version 4 chart. I think the problem is that the <text> element cannot be within the <rect> element according to SVG standards but for the life of me, I cannot work out how to have the <text> element appear just outside the <rect> element. Problematic code is here:

g.selectAll(".bar")
  .data(data)
  .enter().append("rect")
    .attr("class", "bar")
    .attr("y", function(d) { return y(d.Country);    })
    .attr("x", function(d) { return x(d.freqStart); })
    .attr("width", function(d) { return x(d.freqEnd) - x(d.freqStart); })
    .attr("height", y.bandwidth())
  .append("text")
    .attr("class", "label")
    .attr("transform", "rotate(-90)")
    .text(function(d) { return d.Operator; });

The full code can be found at
https://plnkr.co/edit/JiuYKhRxgqtG1osYjJHq?p=preview

Upvotes: 1

Views: 881

Answers (1)

sparta93
sparta93

Reputation: 3854

Yes, you are right. <text> elements cannot be inside <rect> elements. Technically, you can append them but you wont see anything.

That being said, the common way to do this is to append your rects to a <g> element. This way, you can add text labels to the corresponding group accordingly.

This is the portion of your code that I changed. For each bar, we append a new <g> element. In the second part of the code, we add the text labels to the same g elements.

 g.selectAll(".bar")
.data(data)
.enter().append("g")
.attr("class", "bars")
.append("rect")
  .attr("class", "bar")
  .attr("y", function(d) { return y(d.Country);    })
  .attr("x", function(d) { return x(d.freqStart); })
  .attr("width", function(d) { return x(d.freqEnd) - x(d.freqStart); })
  .attr("height", y.bandwidth());

var bars = svg.selectAll(".bars");
bars.append("text")
  .attr("class", "label")
  .attr('transform', 'rotate(-90)')
.attr("y", function(d) { return x(d.freqStart) + 20; })
.attr("x", function(d) { return -y(d.Country) + 5; })
  .text(function(d) { return d.Operator; });

Full working code here - https://plnkr.co/edit/9rUZXl7mfw32sWJih2Ob?p=preview

Upvotes: 3

Related Questions