haki
haki

Reputation: 9779

d3 barplot - why are labels not showing ?

I drew a bar plot with D3. I want to have the x axis values on the bottom and the y values on the bar it self.

for some odd reason the labels are not showing.

would appreciate any one who could take a look at this fiddle.

the relevant section in at the end

// why isnt this showing ??? <-------------------------- right here
// price tags on the bars
svg.selectAll("text")
 .data(y)
 .enter()
 .append("text")
 .text(function(d ,i) { return Math.round(y[i]).toLocaleString() ;}) 
 .attr("y" , function(d) { return height - yscale(d);})
 .attr("x" , function(d, i) { return i * (bar_width + spacing) + bar_width / 4})
 .classed("analysis-result-label" , true);

Upvotes: 1

Views: 1128

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109292

The labels aren't showing because of the way you're selecting and matching data. Each time you're calling .data(), D3 matches the contents of the selection you've made in the step before to the data you pass as an argument. For the second set of labels, you're selecting text elements. This selection will contain the elements you've just added before. Each of the data items will have a matching DOM element and therefore, the .enter() selection will be empty. Hence nothing is added.

The easiest way to avoid this issue is to use the classes you're already assigning to the text elements in the selection. That is,

svg.selectAll("text")

would become

svg.selectAll("text.analysis-result-label")

This means that the second selection will be empty as there are text elements, but not of that particular class, and the rest of the code will work as expected.

Complete jsfiddle here.

Upvotes: 1

Related Questions