Javascript Question

Create Pie chart of frequency count with D3.js

I have a question regarding of d3.js

Let's assume that i have this data:

A A B K J I O N P B N J D G R X S O M H Y D J B T N Y S B N R N E B U D B G D G Y F T K O

i would like to get the frequency count of each letter and make a pie chart with D3.js

Answer

You don't need d3 to do the counting, just simple JavaScript:

var string = "A A B K J I O N P B N J D G R X S O M H Y D J B T N Y S B N R N E B U D B G D G Y F T K O";
var counts = {};
string.split(" ").forEach(function(d) {
  if (!counts[d]) {
    counts[d] = 0;
  }
  counts[d]++;
});

From there the pie chart becomes pretty stock:

<!DOCTYPE html>
<html>

<head>
  <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>

<body>
  <script>
    var string = "A A B K J I O N P B N J D G R X S O M H Y D J B T N Y S B N R N E B U D B G D G Y F T K O";
    var counts = {};
    string.split(" ").forEach(function(d) {
      if (!counts[d]) {
        counts[d] = 0;
      }
      counts[d]++;
    });

    var data = d3.entries(counts);

    console.log(data)

    var width = 360;
    var height = 360;
    var radius = Math.min(width, height) / 2;

    var color = d3.scaleOrdinal(d3.schemeCategory20b);

    var svg = d3.select('body')
      .append('svg')
      .attr('width', width)
      .attr('height', height)
      .append('g')
      .attr('transform', 'translate(' + (width / 2) +
        ',' + (height / 2) + ')');

    var arc = d3.arc()
      .innerRadius(0)
      .outerRadius(radius);

    var pie = d3.pie()
      .value(function(d) {
        return d.value;
      })
      .sort(null);

    var path = svg.selectAll('path')
      .data(pie(data))
      .enter()
      .append('path')
      .attr('d', arc)
      .attr('fill', function(d, i) {
        return color(d.data.key);
      });
  </script>
</body>

</html>