0

I am currently trying to get D3 running in Jupyter Notebook, kind of following this guide: https://www.stefaanlippens.net/jupyter-custom-d3-visualization.html

Using the following code i wanted to add numbers to the bars in the bar chart:

%%javascript

(function(element) {
    require(['d3'], function(d3) {   
        var data = [1, 2, 4, 8, 16, 8, 4, 2, 1]
    var svg = d3.select(element.get(0)).append('svg')
        .attr('width', 400)
        .attr('height', 200);
    
    svg.selectAll('rect')
        .data(data)
        .enter()
        .append('rect')
        .attr('width', function(d) {return d*10})
        .attr('height', 24)
        .attr('x', 0)
        .attr('y', function(d,i) {return i*30})
        .style('fill', 'darkgreen')
    svg.selectAll('rect')
        .append('text')            
        .text('mynumberhere')
        .attr('color', 'FF0000')

})
})(element);

Currently only the bar chart is displayed, but no numbers are displayed. Using the HTML inspector though, i can see that inside the element is a element. Although it is not diplayed. Any ideas why that could be?

1 Answers1

0

It's not possible to append a text to a rect element, they're not meant to have children! You can choose to use g-groups instead, and put both the rect and the text inside:

(function(element) {
  var data = [1, 2, 4, 8, 16, 8, 4, 2, 1]
  var svg = d3.select(element).append('svg')
    .attr('width', 400)
    .attr('height', 200);

  var g = svg.selectAll('g')
    .data(data)
    .enter()
    .append('g');

  g.append('rect')
    .attr('width', function(d) {
      return d * 10
    })
    .attr('height', 24)
    .attr('x', 0)
    .attr('y', function(d, i) {
      return i * 30
    })
    .style('fill', 'darkgreen')
  g
    .append('text')
    .text(function(d) { return d; })
    .attr('color', 'FF0000')
    .attr('dy', 16)
    .attr('dx', 3)
    .attr('x', function(d) {
      return d * 10
    })
    .attr('y', function(d, i) {
      return i * 30
    })
})(document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49