Chartjs-How to create chart from a dict?

0👍

Ignoring the python part, below runnable code illustrates, how it can be done with JavaScript.

const assigned_incidents = [
  {'name': 'Eda', 'case_type': 'Med'},
  {'name': 'Deniz', 'case_type': 'High'},
  {'name': 'Alex', 'case_type': 'Med'},
  {'name': 'Eda', 'case_type': 'High'}
];
const names = [...new Set(assigned_incidents.map(o => o.name))];
const caseTypes = [...new Set(assigned_incidents.map(o => o.case_type))];

new Chart('assigned_incidents', {
  type: 'bar',
  data: {
    labels: names,
    datasets: caseTypes.map(t => ({
      label: t,
      data: names.map(n => assigned_incidents.find(o => o.name == n && o.case_type == t) ? 1 : 0),
      backgroundColor: t == 'Med' ? 'rgb(83, 153, 217)' : 'rgb(128, 27, 128)'
    }))
  },
  options: {
    plugins: {
      tooltip: {
        callbacks: {
          label: ctx => ctx.dataset.label
        }
      }
    },
    scales: {
      x: {
        stacked: true,
      },
      y: {
        stacked: true,        
        ticks: {
          display: false,
          stepSize: 1,
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="assigned_incidents" height="95"></canvas>

Leave a comment