Adding text to top of bar chart by appending text element

Hi all,

I played around and change this original notebook,
to this:

Using join because I wanted to try to add some transitions etc and also learn by trying.
But the text is not showing, I am sure it gets called though because I saw it in the console.

Why doesn’t this work, but the original does?
I am guessing I may be placing it at the wrong location relative to the rects?
Thanks a lot for your help and explanations!

1 Like

You’re appending your text elements to rects, which I wouldn’t expect to work. You probably should create a new g element and append the text there. Also, your join looks more complicated than necessary: you’ve got

.join((enter) => enter
  .append(..)
  ...)

It works, since join does accept a function that allows you to specify different behaviors for enter, update, and exit elements but I don’t think you need that here.

Taking that into account, maybe something like this:

let bar = g
  .selectAll('.bar')
  .data(results)
  .join('rect')
  .attr('class', '.bar')
  .attr('x', d => x(d.flavors))
  .attr('y', d => y(d.sales))
  .attr('width', x.bandwidth())
  .attr('height', d => height - y(d.sales))
  .style('fill', 'steelblue');
svg.append('g')
  .selectAll('text')
  .data(results)
  .join('text')
  .text(d => d.sales)
  .attr('x', d => x(d.flavors) + x.bandwidth() / 2)
  .attr('y', d => y(d.sales) + 15)
  .attr('text-anchor', 'middle')
  .style('font-family', 'sans-serif')
  .style('font-size', 12)
  .style('fill', 'white')

Your text is oddly placed, thus you might want to fiddle with that.

1 Like

Thanks so much for explaining and helping!
I thought the problem was that it gets appended to the rect, I tried appending to bar but didn’t think that I should add a new group element.
I have the join this way because I want to add the update and exit functions later too to play with it a bit. I thought then we need that type of syntax join( enter => enter, update=>update, exit => exit)?

I’ll play around more, thanks a lot!!

1 Like

Yes, that should work. The key issue as far as your question goes is the proper placement of the text.

1 Like

got it, thanks so much!