[Chartjs]-ChartJS radar-chart hover text

1๐Ÿ‘

โœ…

If you wait until Chart.js version 3.8 is getting released you can use object notation with radar charts:

let dataValues = [{
    value: 100,
    text: 'f'
  },
  {
    value: 120,
    text: 'd'
  },
  {
    value: 80,
    text: 'q'
  },
  {
    value: 100,
    text: 'b'
  },
  {
    value: 90,
    text: 'z'
  },
  {
    value: 110,
    text: 'efw'
  },
  {
    value: 100,
    text: 'ffew'
  },
  {
    value: 100,
    text: 'ffdddew'
  },
  {
    value: 100,
    text: 'fffff'
  }
]

const sum = dataValues.reduce((a, b) => a.value + b.value, 0);
const avg = sum / dataValues.length;
const sorted = [...dataValues].sort(function(a, b) {
  return a.value - b.value;
})

const data = {
  labels: [
    'Signal 1',
    'Signal 2',
    'Signal 3',
    'Signal 4',
    'Signal 5',
    'Signal 6',
    'Signal 7',
    'Signal 8',
    'Signal 9'

  ],
  datasets: [{
    label: '9 signals',
    data: dataValues,
    fill: true,
    backgroundColor: 'rgba(210, 203, 203, 0.4)',
    borderColor: 'rgb(210, 203, 203, 0.6)',
    pointBackgroundColor: function(context) {
      const index = context.dataIndex;
      const value = context.dataset.data[index].value;

      return value < sorted[3].value ? 'blue' :
        value < sorted[5].value ? 'green' :
        value < sorted[7].value ? 'orange' :
        'red';
    },
    pointBorderColor: '#fff',
    pointHoverBackgroundColor: '#fff',
    pointHoverBorderColor: 'rgb(255, 99, 132)'
  }]
};

const config = {
  type: 'radar',
  data: data,
  options: {
    plugins: {
      tooltip: {
        callbacks: {
          label: (ctx) => (`${ctx.dataset.label}: ${ctx.parsed.r} ${ctx.dataset.data[ctx.dataIndex].text}`)
        }
      }
    },
    parsing: {
      key: 'value'
    },
    elements: {
      line: {
        borderWidth: 3
      },
      point: {
        pointRadius: 5
      }
    },
    scales: {

      r: {
        angleLines: {
          lineWidth: 2
        },
        grid: {
          circular: true,
          lineWidth: 2
        }
      }
    }
  }
};


let myChart = new Chart(
  document.getElementById('myChart'),
  config
);
<div class="chartBox">
  <canvas id="myChart"></canvas>
  <script src="https://www.chartjs.org/dist/master/chart.js"></script>
</div>

Leave a comment