我想在 Chart.js 中制作一个中心为空的雷达图,如下所示:
因此,在下面的工作示例中,我希望使角线(从中心开始的线)从 2 开始,并将中心设置为白色五边形:
radarChart = new Chart('radarCanvas',{
"type": "radar",
"data": {
"labels": [
"Management & Leadership",
"Education & Teaching",
"Research",
"Impact",
"Team"
],
"datasets": [
{
"label": "4-3-21",
"backgroundColor": "rgb(231,74,59,0.5)",
"hoverBackgroundColor": "rgb(231,74,59,0.8)",
"borderColor": "rgb(231,74,59)",
"data": [
2.7,
3.8,
4.6,
2.2,
3.2
]
}
]
},
"options": {
"responsive": true,
"maintainAspectRatio": false,
"scale": {
"angleLines": {
"color": "rgb(90,92,105)"
},
"gridLines": {
"color": "rgb(90,92,105)"
},
"ticks": {
max: 10,
min: 0,
stepSize: 2,
}
}
}
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<canvas id="radarCanvas" width="400" height="400"></canvas>
我到目前为止尝试过的解决方案及其缺点:
更改角度线选项:文档中不存在允许这样做的属性
绘制具有白色背景颜色的数据集:上图的数据集[2,2,2,2,2]应该完美覆盖角线,但chart.js将背景颜色与覆盖数据集混合,导致非白色覆盖,我还发现无法在图例中翻转该数据集的标签,从而导致不同数据集的标签旁边有一个空标签
互联网:我发现开发人员可以提及,但一直无法找到解决方案..
您可以尝试通过将刻度刻度设为负值 (
min: -2
),然后使用 borderDash
配置来实现类似的效果。但是,如果图表的大小发生变化,您还需要相应调整 angleLines
中的第四个数组编号。下面的代码应该针对我的屏幕尺寸呈现类似这样的内容:
borderDash
radarChart = new Chart('radarCanvas', {
"type": "radar",
"data": {
"labels": [
"Management & Leadership",
"Education & Teaching",
"Research",
"Impact",
"Team"
],
"datasets": [{
"label": "4-3-21",
"backgroundColor": "rgb(231,74,59,0.5)",
"hoverBackgroundColor": "rgb(231,74,59,0.8)",
"borderColor": "rgb(231,74,59)",
"data": [
2.7,
3.8,
4.6,
2.2,
3.2
]
}]
},
"options": {
"responsive": true,
"maintainAspectRatio": false,
"scale": {
"angleLines": {
"color": "rgb(90,92,105)",
"lineWidth": 1,
"borderDash": [
0,
0,
0,
28,
150,
250
]
},
"gridLines": {
"color": "rgb(90,92,105)"
},
"ticks": {
"max": 10,
"min": -2,
"stepSize": 2,
"callback": function(tickValue, index, ticks) {
if (tickValue >= -0) {
return tickValue
}
return null
},
},
"max": 10,
"min": -4,
"beginAtZero": false
}
}
})
这仅在您也不需要显示刻度线(我的情况)时才有效,否则白色多边形将与它们重叠。
(代码取自 @Nicodemuz 的答案,但针对 Chart.js v4.4.1 进行了更新)
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<canvas id="radarCanvas" width="400" height="400"></canvas>
radarChart = new Chart('radarCanvas', {
"type": "radar",
"data": {
"labels": [
"Management & Leadership",
"Education & Teaching",
"Research",
"Impact",
"Team"
],
"datasets": [
{
"label": "4-3-21",
"backgroundColor": "rgb(231,74,59,0.3)",
"hoverBackgroundColor": "rgb(231,74,59,0.6)",
"borderColor": "rgb(231,74,59)",
"data": [
2.7,
3.8,
4.6,
2.2,
3.2
]
},
{
"label": "",
"backgroundColor": "white",
"borderWidth": 0,
"pointRadius": 0,
"hoverBorderWidth": 0,
"hoverPointRadius": 0,
"data": [
0,0,0,0,0
]
},
]
},
"options": {
"scales": {
"r": {
"max": 10,
"min": -4,
"beginAtZero": false,
"ticks": {
"display": false
}
}
}
}
})