score:2

Accepted answer

The problem is this line when adding the labels:

svg.selectAll('text')

If you have drawn the axes at this point. There will be text elements and the selection above will not be empty. Calling .data() on it causes D3 to match data elements to DOM elements in the selection. In this case, everything is matched and therefore the .enter() selection is empty and no new labels are added.

It works if you run this code first because there are no text elements, the selection is empty and no data is matched. To prevent this, you can for example identify the label text elements explicitly with a class:

svg.selectAll('text.label')
    .data(dataset)
    .enter()
        .append('text')
        .attr("class", "label")
        .text(Math.floor)
        .attr('class', 'data-label')
        .attr('x', function (d, i) { return x(i); })
        .attr('y', function (d, i) { return y(d + 1); });

With this code, it doesn't matter whether you run it before or after adding the axes.


Related Query