[Chartjs]-Chart.js – How to customize specific grid line depending on tick value

1πŸ‘

βœ…

In my opinion, the logically correct answer is to define grid.borderDash as follows:

grid: {
  ...
  borderDash: ctx => ctx.tick.value == 100 ? [8, 4] : []
},

To make it work however, I had to use ctx.tick.value == 95 (This could be a bug in Chart.js). Please take a look at your amended code and see how it works.

let dataValues = [100, 120, 80, 100, 90, 110, 100, 100, 100]

const sum = dataValues.reduce((a, b) => a + b, 0);
const avg = sum / dataValues.length;
const sorted = [...dataValues].sort(function(a, b) {
  return a - b;
});
const data = {
  labels: dataValues.map((v, i) => 'Signal ' + (i + 1)),
  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) {
        var index = context.dataIndex;
        var value = context.dataset.data[index];
        return value < sorted[3] ? 'blue' :
          value < sorted[5] ? 'green' :
          value < sorted[7] ? 'orange' :
          'red';
      },
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgb(255, 99, 132)'
    }
  ]
};

const config = {
  type: 'radar',
  data: data,
  options: {
    elements: {
      line: {
        borderWidth: 3
      },
      point: {
        pointRadius: 5
      }
    },
    scales: {
      r: {
        suggestedMin: 70,
        angleLines: {
          lineWidth: 2
        },
        grid: {
          circular: true,
          lineWidth: 2,
          borderDash: ctx => ctx.tick.value == 95 ? [8, 4] : []
        },
        ticks: {
          stepSize: 5
        }
      }
    }
  }
};

let myChart = new Chart('myChart',
  config
);
.chartBox {
  width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<div class="chartBox">
  <canvas id="myChart"></canvas>
</div>

Leave a comment