score:43

Accepted answer

In your second block of code, you are only appending one text element, hence only one of them is appearing. What you need to do is to append the text similar to your first block, i.e. with the .enter() selection. For this, you have two choices. You can either save and reuse the .enter() selection, or assign different classes to the two kinds of text to be able to distinguish between them.

Option 1:

var texts = svg.selectAll("text")
                .data(dataset)
                .enter();

texts.append("text")
     .text(function(d){
                    return d.metric;
                })
     // set position etc.

texts.append("text")
     .text(function(d){
                    return d.value;
                })
     // set position etc.

Option 2:

svg.selectAll("text.title")
                .data(dataset)
                .enter()
                .append("text")
                .attr("class", "title")
                .text(function(d){
                    return d.metric;
                })
     // set position etc.

svg.selectAll("text.value")
                .data(dataset)
                .enter()
                .append("text")
                .attr("class", "value")
                .text(function(d){
                    return d.value;
                })
     // set position etc.

The first option is obviously shorter, but depending on what else you want to do, the second option may be preferable -- if you want to modify the text afterwards, it will be a lot easier if you can distinguish between the two kinds of text. You can also use the different classes to give different CSS styles.


Related Query

More Query from same tag