找不到一个简单的例子:尝试在Chart.js中创建一条曲线并添加相当简单的标签。已经接近了,但需要一些帮助,因为我的JS不是我的强项,文档有点混乱。因此,我有一条带有4个点(x,y)的线和第二个带有1个点的数据集:
<!DOCTYPE html>
<html>
<body>
<div>
<canvas id="linechart" width="500" height="500" style="display: block; box-sizing: border-box; height: 400px; width: 400px;"/>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.0.0/dist/chart.min.js"/>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"/>
<script>
var linedata = {
datasets: [
{
data: [{x:70,y:50}]},
{
datasets: [{
// Change options only for labels of THIS DATASET
datalabels: {
color: 'yellow'
}
}],
data: [{
x: 0,
y: 90
}, {
x: 69,
y: 78
}, {
x: 150,
y: 55
}, {
x: 165,
y: 0
}
],
showLine: true,
fill: false,
lineTension: 0.4,
bezierCurve: true,
borderColor: 'rgba(10, 200, 40, 1)'
}
]
};
var chartOptions = {
plugins: {
datalabels: {
color: 'blue',
labels: {
title: {
font: {
weight: 'bold'
}
},
value: {
color: 'green'
}
}
}
},
animation: {
duration: 0
},
responsive: false,
maintainAspectRatio: true,
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
type: 'linear',
position: 'bottom',
ticks: {
stepSize: 10,
max: 180
}
}],
yAxes: [{
ticks: {
stepSize: 10,
max: 100
}
}]
}
};
var lineID = document.getElementById('linechart').getContext('2d');
var lineChart = new Chart(lineID, {
type: 'scatter',
data: linedata,
options: chartOptions,
plugins:[ChartDataLabels]
});
</script>
</body>
</html>
我所需要的是将每个点定义为“预定义文本”+值/的语法,例如,第二个点应表示“压力:65'.
我相信答案就在这里:但是https://chartjs-plugin-datalabels.netlify.app/guide/formatting.html#data-transformation我的JS还不够好....
1条答案
按热度按时间2j4z5cfb1#
当然,这将有助于尝试在数据标签中使用格式化程序函数
https://chartjs-plugin-datalabels.netlify.app/guide/formatting.html#custom-labels
下面的return语句将给予为点定义的标签,可根据需要进行更改
下面的示例是您需要的语法