-1

I am having a little bit of problems when it comes to using the ChartJS library with React.js. Basically, what I am trying to do is to fetch the data from the specific endpoint and when I get that data I want to populate the chart with it. The problem that I am having is to find out how to populate the entire box that is between two values (X and Y).

I am going to show you the design you have a better picture of what I am trying to do:

Design

enter image description here

This is the design of the project that I am working on. Numbers inside the boxes are not important as they represent number of people inside that range, for example the number 23 means people that have a score between 65-70 (Y axis) and have a 24-28 hourly rate (X axis).

Is it possible to achieve something like this using ChartJS or should I opt out of it and start using some other library?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Samke11
  • 385
  • 5
  • 17

1 Answers1

1

This can be done with chartjs-plugin-annotation box annotations and label annotations as follows:

const data = [
  { x: 4, y: 5, width: 4, height: 5, label: 4 },
  { x: 4, y: 10, width: 4, height: 5, label: 7 },
  { x: 8, y: 15, width: 4, height: 5, label: 12 },
  { x: 8, y: 25, width: 4, height: 5, label: 16 },
  { x: 12, y: 5, width: 4, height: 5, label: 8 },
  { x: 16, y: 0, width: 4, height: 5, label: 6 },
  { x: 20, y: 10, width: 4, height: 5, label: 12 }, 
  { x: 24, y: 20, width: 4, height: 5, label: 18 },
  { x: 24, y: 30, width: 4, height: 5, label: 9 },
];

const rectangles = data.map(o => ({
  type: 'box',
  backgroundColor: 'rgba(0, 0, 254, 0.4)',
  xMin: o.x,
  yMin: o.y,
  xMax: o.x + o.width,
  yMax: o.y + o.height
}));

const labels = data.map(o => ({
  type: 'label',
  content: o.label,  
  color: 'white',
  font: {
    size: 16    
  },
  position: {
    x: 'center',
    y: 'center'
  },
  xValue: o.x + o.width / 2,
  yValue: o.y + o.height / 2
}));

new Chart('myChart', {
  type: 'scatter',
  options: {
    plugins: {
      annotation: {
        annotations: rectangles.concat(labels)
      }
    },
    scales: {
      x: {
        position: 'top',
        suggestedMin: 0,
        suggestedMax: 32,
        ticks: {
          stepSize: 4
        }
      },
      y: {
        suggestedMin: 0,
        suggestedMax: 35,
        ticks: {
          stepSize: 5
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/1.4.0/chartjs-plugin-annotation.min.js"></script>
<canvas id="myChart"></canvas>
uminder
  • 23,831
  • 5
  • 37
  • 72