Displaying Charts

Because CloudTables exposes the APIs for DataTables and Editor, you can integrate the table with other libraries and services. For example, you may wish to send the edited data to a server, or as in the case of this example, you can read the data with visualisation tools.

Here, we are using Chart.js to create a pie-chart of the data displayed in the table. If you filter the table, try entering text in the "Search" input box, the pie-chart updates to match the search results.

This example was achievable by adding the following code into the document:
// Collect and bin the data from the table for the chart
function chartData (table, column) {
  let counts = {};

  // Count the number of entries for each office
  table
    .cells(null, column + ':title', {
    order: 'index',
    search: 'applied'
  })
  .render('display')
  .each(function (val) {
    if (counts[val]) {
      counts[val] += 1;
    }
    else {
      counts[val] = 1;
    }
  });

  // And map it to values and labels
  return {
    values: Object.values(counts),
    labels: Object.keys(counts),
  };
}

// Listen for the CloudTable being ready
document.addEventListener('ct-ready', (e) => {
  let options = {
    type: 'pie',
    data: {
      datasets: [{
        backgroundColor: [
          'rgb(255, 99, 132)',
          'rgb(255, 159, 64)',
          'rgb(255, 205, 86)',
          'rgb(75, 192, 192)',
          'rgb(54, 162, 235)',
          'rgb(153, 102, 255)',
          'rgb(201, 203, 207)',
        ],
        data: [],
        label: 'Staff count per office'
      }],
      labels: []
    },
    options: {
      responsive: true
    }
  };
  let ctx = document.getElementById('chart-area').getContext('2d');
  let pie = new Chart(ctx, options);

  // On each DataTable draw, refresh the chart's data
  e.table.on('draw', function () {
    let data = chartData(e.table, 'Office');

    options.data.datasets[0].data = data.values;
    options.data.labels = data.labels;

    pie.update();
  });
});

Other examples