1
votes

Here's the Fiddle.

I've created a responsive histogram.

And I wanted to add the data labels to it.

I tried with this code. But it didn't help me out.

svg.selectAll("text")
            .data(histogram)
            .enter()
            .append("text")
            .attr("x", function(d) { return x(d.x); })
            .attr("y", function(d) { return y(d.y); })
        .text(function(d) { return d; })

Please help me in solving this.

I guess I'm doing it all right.

But I don't know why the text elements aren't created yet.

Thanks in advance!!

1

1 Answers

1
votes

There are 3 small problems with your code:

  • The .selectAll("text") selects the text elements that were added for the axes, matches the given data against them and your .enter() selection is empty. Hence no new text is added. You can fix this by e.g. assigning a distinguishing class to the text labels.
  • The y position should be height - y(d.y).
  • You probably don't want to show the entire object as a label, but just d.y.

The following code addresses these issues.

svg.selectAll("text.label")
        .data(histogram)
        .enter()
        .append("text")
        .attr("class", "label")
        .attr("x", function(d) { return x(d.x); })
        .attr("y", function(d) { return height - y(d.y); })
        .text(function(d) { return d.y; })

Complete demo here.