kaboom
kaboom

Reputation: 307

d3 append an array of text

I am using d3 to draw a boxplot. I want to append headers on the x axis (this is not the labels/tick marks for x axis)

for some reasons, the headers dont appear on the page, and there is no error reported. I have check the array's values and they are correct. E.g [A, B, C]

FYI, the 'text' element is not appended on svg element afterward

This is my code

if (xAxisHeaderAr.length > 0) {
        console.log("inside ok!");
        console.log("xAxisHeaderAr:" + xAxisHeaderAr);//[A,B,C] this is correct values!

        svg.selectAll("text")
            .data(xAxisHeaderAr)
            .enter()
            .append("text")
            .text(function (d) { return d; }) // should return A then B then C
                                                 // but nothing happens here

            .attr({
                "class": "xAxisSubHeader",
                "text-anchor": "middle",
                "x": (w/2*padding)/4, 
                "y": padding - 10
            });

    }

Upvotes: 0

Views: 3394

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109292

The problem is that you've drawn the axis already, which contains text elements. These are, as pointed out in the comment, selected when you do a svg.selectAll("text"). The way D3's data matching works by default is that it uses the index within an array to match, i.e. the first data item is matched to the first element in the selection and so on. This means in this case that all data are matched to text elements and the .enter() selection is empty. Hence nothing gets appended.

The only way to solve this in your case is to assign a distinguishing class to the labels and select based on that:

svg.selectAll("text.label")
        .data(xAxisHeaderAr)
        .enter()
        .append("text")
        .attr("class", "label")
        .text(function (d) { return d; });

Another way would be to tell D3 how to match data by supplying a key function to .data(), but this is not an option in your case as the data underlying the labels and the x axis labels is exactly the same (if I interpret your variable name correctly).

Upvotes: 1

Related Questions