Quick doughnut and pie charts with a radial timer

If you've been trying out the Configurable circular timer with D3 or playing around with Example of clock using d3 configurable timer you'll have seen how easy it is to create a versatile timer by just configuring a few objects. 

The timer uses D3 arcs - which are actually the building blocks for piecharts and dougnut charts.  D3 has great tools for building these kind of layouts but if you are already using the timer and need something very basic, it's easy to configure it to be a chart instead - these turned out just fine for what I needed to report player score summaries in BigQuiz app


You can play around with the options in the codepen above, but here's the code. As you can see there's really not much to it.  Whether the charts are pies or doughnut is controlled by the innerRatio. set it to 0 and you have a pie. something between 0 and 1 becomes a doughnut. Amd you can choose to animate them or not by tweaking the duration.
(function() {
  var chartOptions = {
    duration:500,
    height:120,
    width:120,
    values: {
      classes: "mu--text-caption mui--text-center",
      styles: "font-size:.7em;text-anchor:middle;"
    }
  };

  function getChartData(data) {

    var sum = d3.sum(data);
    var color = d3.scale.category10();
    var angle = 0;
    return data.map(function(d, i) {
      var x = {
        dataName: 'name' + i,
        start: {
          angle: angle,
          fill: color(i),
          value: 0
        },
        finish: {
          angle: angle + d / sum,
          fill: color(i),
          innerRatio: .2,
          value: d
        }
      };
      angle += d / sum;
      return x;
    });
  }

  var player = new DashTimer('#player').init(chartOptions);
  var allPlayers = new DashTimer('#allplayers').init(chartOptions);
  var playerCorrect = new DashTimer('#playercorrect').init(chartOptions);
  var allPlayersCorrect = new DashTimer('#allplayerscorrect').init(chartOptions);
  
  player.setData(getChartData([9,11,20,17,18])).start(0);
  allPlayers.setData(getChartData([53,76])).start(0);
  playerCorrect.setData(getChartData([17,100,90])).start(0);
  allPlayersCorrect.setData(getChartData([25,89,120,56,77,99])).start(0);
  d3.select('#catname').text('some charts made with a timer');
})();








For more like this, see Google Apps Scripts snippets. Why not join our forumfollow the blog or follow me on twitter to ensure you get updates when they are available. 




Comments