简体   繁体   中英

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. Eg [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
            });

    }

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, ie 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM