Session Timing Metrics

Let’s say you want to create visualizations for:

  • when things happen in a session
  • how long sessions last
  • how much is happening at a given point in time

Here are a few recipes for how to create time-related charts with Keen, D3 and Underscore.

Average Number of Sessions by Hour of Day

You can use D3’s nest function to help calculate the average number of sessions by hour of day when you have a multi-day timeframe. You can create an area chart with Keen’s data visualization library.

var client = new Keen({
  projectId: "YOUR_PROJECT_ID",
  readKey: "YOUR_READ_KEY"
});

Keen.ready(function(){

  var sessionsByHour = new Keen.Query('count', {
      event_collection: 'session_end',  // i.e. Completed sessions
      timeframe: timeframe,
      interval: 'hourly',
  });

  var sessionsChart = new Keen.Dataviz()
    .el(document.getElementById('sessions-chart'))
    .chartType('areachart')
    .height(300)
    .chartOptions({
      chartArea: {
          left: '10%',
          width: '90%',
          top: '10%',
          height: '80%'
      },
      isStacked:true,
      legend: { position: 'none' }
    })
    .prepare(); // start spinner


  client.run(sessionsByHour, function(err, res){
      // if (err) throw('Error!');

      // Normalize the dates
      var now = new Date();
      var nestedData = d3.nest()
      .key(function(d) {
          // Use the hour of day as your key
          return new Date(d.timeframe.start).getHours();
      })
      .rollup(function(leaves) {
          var total = d3.sum(leaves, function(d) { return d.value; });
          // Use the average number of sessions at a given hour as your value
          return {
              denominator: leaves.length,
              total: total,
              avg: total / leaves.length
          };
      })
      .entries(res.result);

      // Format your data so it can be drawn as an areachart
      var result = nestedData.map(function(d){
          var start = new Date(now);
          start.setHours(d.key);
          return {
              value: d.values.avg,
              timeframe: {
                  start: start.toISOString(),
                  end: new Date(start.getTime() + (60 * 60 * 1000)).toISOString()
              }
          };
      });

      // Render visualization
      sessionsChart
        .parseRawData({ result: result })
        .render();

  });

Timing Metrics Areachart

Events by Hour of Day

If you’d like to see how many events happen at any given hour of the day, you can use Keen’s hourly interval and count the events accordingly.

var client = new Keen({
  projectId: "YOUR_PROJECT_ID",
  readKey: "YOUR_READ_KEY"
});

Keen.ready(function(){

  var purchasesByHour = new Keen.Query('count', {
      event_collection: 'purchase',  // i.e. The event we're tracking
      timeframe: timeframe,
      interval: 'hourly'
  });

  var purchasesChart = new Keen.Dataviz()
    .el(document.getElementById('purchases-chart'))
    .chartType('linechart')
    .height(300)
    .prepare(); // start spinner

  //Draw the visualization into a div
  client.run(purchasesByHour, function(err, response) {
      // if (err) throw('Error!');
      purchasesChart
        .parseRequest(this)
        .render();
  });

});

});

Count by Hour

Average Cart Size by Hour of Day

One way to calculate how many items, on average, are in a user’s cart by hour of day, entails setting up your data model so you can keep track of a session’s state. In the example below, state is the event collection and number_tems_in_cart is the event property we’re looking at. Establishing an event property for local_time_hour (e.g. 0, 1, 2… 23) also simplifies the process of analyzing cart size (or anything else) by hour of day.

var client = new Keen({
  projectId: "YOUR_PROJECT_ID",
  readKey: "YOUR_READ_KEY"
});

Keen.ready(function(){

  var queueCount = new Keen.Query('average', {
      event_collection: 'screen_view',
      timeframe: timeframe,
      target_property: 'state.number_items_in_cart',
      group_by: 'event.local_time_hour',
  });

  var queueChart = new Keen.Dataviz()
    .el(document.getElementById('queue-chart'))
    .height(300)
    .chartOptions({
      legend: { position: 'none' },
      hAxis: {
        title: 'Hour of Day'
      },
      vAxis: {
        title: 'Average Cart Size',
        minValue: 0
      }
    })
    .prepare(); // start spinner

  client.run(queueCount, function(err, response){
      // if (err) throw('Error!');

      queueChart
        .parseRawData({
          // uses underscore _.map method
          result: _.map(response.result, function(item){
            return {key: item['event.local_time_hour'], value: item.result};
          })
        })
        .render();

  });

});

Average Column Chart