user1899082
user1899082

Reputation:

Adding text to a newly added element

This is the whole code you need:

https://raw.github.com/alignedleft/d3-book/master/chapter_09/25_adding_values.html

It is referencing D3 locally but for faster work you can just refrence it from its website like this instead:

<script src="http://d3js.org/d3.v3.min.js"></script>

It will create some chart like this:

enter image description here

Notice the newly added charts on the ones that don't have a text label on them.

Part of code that is adding labels is towards the very end of the code and is this:

            svg.selectAll("text")
               .data(dataset)
               .transition()
               .duration(500)
               .text(function(d) {
                    return d;
               })
               .attr("x", function(d, i) {
                    return xScale(i) + xScale.rangeBand() / 2;
               })
               .attr("y", function(d) {
                    return h - yScale(d) + 14;
               });

As an exercise I am trying to modify the code so I can update the new bars also with their text data, but still couldn't figure it out. How would you do that?

Upvotes: 0

Views: 83

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

You need to handle the .enter() selection. The code would look like this.

svg.selectAll("text")
           .data(dataset)
           .enter()
           .append("text")
           .text(function(d) {
                return d;
           })
           .attr("x", function(d, i) {
                return xScale(i) + xScale.rangeBand() / 2;
           })
           .attr("y", function(d) {
                return h - yScale(d) + 14;
           });

Have a look at this tutorial for more information.

Upvotes: 2

Related Questions