Chart based on multi-choice field

I'm trying to create a pie chart using a Choice, Checkboxes (allow multiple selections) column.
some entries have more than one checkbox checked.

Any help is greatly appreciated.

Hello @jaitsujin,

You need to count selected options using the code. You can find the example in this post:

Ok I finally got something going, but running into a new issue. In design mode, the preview works just fine, but the moment I save and exit out to go back to the pack I'm getting an error. Well better nothing really happens.

Filtered raw data for year "2024": (4) [{…}, {…}, {…}, {…}]
VM20661:48 chart: undefined
VM20661:60 Chart is not ready. Skipping update.

const filtered is the correct data, but i can't seem to be able to update the chart.

This is the code for both tabs. Any help is greatly appreciated.

// ==== Data Source Advanced ==== //
window.totalCountGlobal = 0;
var handlers = {};
handlers.init = function (data, logger) {
  return true;
};

handlers.requestInit = function (query, logger) {
  return true;
};

handlers.requestSuccess = function (data, logger) {
  return true;
};

handlers.requestError = function (error, logger) {
  return $.Deferred().reject(error);
};

handlers.aggregationSuccess = function (data, logger) {
  return true;
};

handlers.aggregationError = function (error, logger) {
  return $.Deferred().reject(error);
};

handlers.finish = function (data, logger) {

  var newData = [];
  var counts = {};

  // Loop through the data and group by Installation and Year
  data.items.forEach(function (item) {
    var installations = item.Installation;
    var year = item.Year; // Ensure Year is part of each item
    // console.log(item)

    if (Array.isArray(installations)) {
      installations.forEach(function (val) {
        if (val) {
          const key = val + '-' + year; // Combine Installation and Year as key
          counts[key] = (counts[key] || 0) + 1;
        }
      });
    } else {
      const key = installations + '-' + year; // For single installations
      counts[key] = (counts[key] || 0) + 1;
    }
  });

  // Transform the counts into an array of objects
  for (var key in counts) {
    const [installation, year] = key.split('-');
    newData.push({
      Installation: installation,
      Year: year,
      Count: counts[key]
    });
  }

  // Sort data by Count descending
  newData.sort(function (a, b) {
    return b.Count - a.Count;
  });

  // Calculate the total count across all years and installations
  var totalCount = newData.reduce(function (sum, item) {
    return sum + item.Count;
  }, 0);

  window.totalCountGlobal = totalCount;

  // Save the processed data globally for filtering later
  window.rawChartData = [...newData];  // Store this data for later use in filtering
  //logger.debug('Sorted data: ', newData);
  logger.debug('Total Installation count: ' + totalCount);

  data.items = newData;
  return true;
};


// ==== Dashboard Advanced ==== //

// Add dropdown for year selection
var css = '#yearDropdown { background: #eee; border: 1px solid #464646; padding: 5px; font-size: 14px; }';
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
head.appendChild(style);
style.type = 'text/css';
style.appendChild(document.createTextNode(css));

var handlers = {};
handlers.preRender = function (config, logger, processor, el) {
  // Create the year dropdown filter
  $('#yearFilter').remove();
  el.parent().append('<div id="options" style="text-align: center;"></div>');
  $('#options').append('<div id="yearFilter" style="text-align: center;">Filter by Year: <select id="yearDropdown"></select></div>');

  var chart = el.data("kendoChart");

  if (!window.rawChartData || !Array.isArray(window.rawChartData)) {
    logger.error('rawChartData is not available. Chart will not filter properly.');
    return true;
  }

  // Get the unique years for the dropdown
  var years = [...new Set(window.rawChartData.map(i => i.Year))].sort();
  $('#yearDropdown').append('<option value="All">All</option>');
  years.forEach(y => $('#yearDropdown').append(`<option value="${y}">${y}</option>`));

  // Function to filter the data based on the selected year
  function filterAndUpdateChart(selectedYear) {
    const filtered = (selectedYear === 'All')
      ? window.rawChartData
      : window.rawChartData.filter(i => i.Year === selectedYear);

    console.log(`Filtered raw data for year "${selectedYear}":`, filtered);

    const counts = {};
    filtered.forEach(item => {
      const installations = Array.isArray(item.Installation) ? item.Installation : [item.Installation];
      installations.forEach(inst => {
        const key = inst + '-' + item.Year;
        counts[key] = (counts[key] || 0) + 1;
      });
    });

    const total = filtered.reduce((sum, i) => sum + i.Count, 0);
    console.log("chart:", chart)
    // Make sure chart is defined before updating it
    if (chart) {
      chart.setOptions({
        title: {
          text: `Cumulative Taskers by Installation (Total: ${total})`
        }
      });

      chart.setDataSource(new kendo.data.DataSource({ data: filtered }));
      chart.refresh();
    } else {
      console.warn('Chart is not ready. Skipping update.');
    }
  }


  filterAndUpdateChart('All'); // Load everything initially

  // Handle year dropdown change
  $('#yearDropdown').on('change', function () {
    const selectedYear = $(this).val();
    logger.debug('Year selected: ', selectedYear);
    filterAndUpdateChart(selectedYear);
  });

  // Chart styling
  config.title = {
    text: "Cumulative Taskers by Installation (Total: " + (window.totalCountGlobal || 0) + ")",
    color: "#464646",
    font: "22px 'Segoe UI Light',sans-serif"
  };

  config.valueAxis.labels.color = "#464646";
  config.valueAxis.labels.font = "16px 'Segoe UI Light',sans-serif";
  config.categoryAxis.labels.color = "#464646";
  config.categoryAxis.labels.font = "18px 'Segoe UI Light',sans-serif";
  config.seriesDefaults.labels.color = "#464646";
  config.seriesDefaults.labels.font = "20px 'Segoe UI',sans-serif";
  config.legend.labels = {
    color: "#464646",
    font: "16px 'Segoe UI Light',sans-serif"
  };

  config.series[0].color = "#a0a0a0";

  return true;
};

@jaitsujin,

Charts had an issue with performance yesterday. This error could be related to it.

Please try publishing chart again now.

Hi,
I'm on-prem 2019. This might be a different issue.

@jaitsujin,

Could you please share the errors from the browser console when saving the chart set up.

Can you add another chart to the same page with no custom code and save it. Does it work?