score:1

Accepted answer

According to your comment, the value of d['ROBBERY'] is 951. So, what you're getting is the expected behaviour (hint: 951 has a length of 3).

The data() method accepts only three things:

  • An array;
  • A function;
  • Nothing.

So, when you pass a number (actually, a string) to data(), it will treat it as an array.

Have a look here:

var body = d3.select("body")
var data = "951";
var p = body.selectAll(null)
  .data(data)
  .enter()
  .append("p")
  .text(String)
<script src="https://d3js.org/d3.v4.min.js"></script>

Solution:

Don't use data() if you have just a single text element to append. Or, alternatively, wrap d['ROBBERY'] in [], turning it into an array:

var body = d3.select("body")
var data = "951";
var p = body.selectAll(null)
  .data([data])
  .enter()
  .append("p")
  .text(String)
<script src="https://d3js.org/d3.v4.min.js"></script>

PS: The only reason that in your code you're getting 951 three times is that you're using...

.text(function () {
    return myLabel;
})

... to print the texts. If you used the data...

.text(function (d) {
    return d;
})

... you would have just 9, 5 and 1. Try it and you'll see.


Related Query

More Query from same tag