Chart.js -如何根据刻度值定制特定的网格线



我有一张雷达图,里面有"100"表示一个特征的全局平均值。

为了使图表更具可读性,我想只将表示100值的网格线标记为虚线。

有办法做到这一点吗?

当前图表代码在这里:jsfiddle.

const config = {
type: 'radar',
data: data,
options: {
elements: {
line: {
borderWidth: 3
},
point: {
pointRadius: 5
}
},
scales: {
r: {
angleLines: {
lineWidth: 2
},
grid: {
circular: true,
lineWidth: 2
}
}
}
}
};

在我看来,逻辑上正确的答案是定义grid.borderDash如下:

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

为了使它工作,然而,我不得不使用ctx.tick.value == 95(这可能是Chart.js中的一个bug)。请看一下修改后的代码,看看它是如何工作的。

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>

最新更新