我有一个chartjs线图的设置,我想以固定的数值在图表上画一条水平标注线。 但是 无事生非 并且在控制台中没有错误。
我已经把 chartjs-plugin-annotation.js这样的包含进去了。
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.min.js"></script>
然后把这个添加到 options:
(应该在图表上添加一条2px粗的线作为值 "25")。
annotation: {
drawTime: 'afterDraw',
annotations: [{
type: 'line',
id: 'line',
mode: 'horizontal',
scaleID: 'y-axis-0',
value: 25,
borderWidth: 2,
borderColor: 'black'
}]
},
图表的完整代码在这里
var temperaturechart = new Chart($('#temperaturechart'), {
type: 'line',
data: {
datasets: [{
label: 'Temperature',
backgroundColor: 'rgba(252, 132, 3, 0.1)',
borderColor: 'rgba(252, 132, 3, 1)',
data: [{"x":"2020-05-21 14:00:00","y":27.28},{"x":"2020-05-21 16:00:00","y":28.64},{"x":"2020-05-21 18:00:00","y":29.83},{"x":"2020-05-21 20:00:00","y":20.24},{"x":"2020-05-21 22:00:00","y":21.63},{"x":"2020-05-22 00:00:00","y":30.34},{"x":"2020-05-22 02:00:00","y":19.01},{"x":"2020-05-22 04:00:00","y":18.88}],
}]
},
options: {
annotation: {
drawTime: 'afterDraw',
annotations: [{
type: 'line',
id: 'line',
mode: 'horizontal',
scaleID: 'y-axis-0',
value: 25,
borderWidth: 2,
borderColor: 'black'
}]
},
aspectRatio: 2.5,
legend: {
display: false
},
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day',
unitStepSize: 1,
displayFormats: {
'day': 'MMM DD'
}
},
scaleLabel: {
display: false,
labelString: 'Date'
},
gridLines: {
tickMarkLength: 8,
zeroLineColor: 'rgba(0, 0, 0, 0.1)'
},
ticks: {
maxRotation: 90,
minRotation: 45,
padding: 10
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Temperature'
}
}]
},
}
});
我犯了一个愚蠢的错误,既包含了Chart.min.js,后来又把Chart.bundle.min.js也包含进去了。
所以类似这样。
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.min.js"></script>
...other code...
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
删除后来的Chart.bundle.min.js就解决了这个问题。