对于第一个问题,您必须禁用图例:
plugins: {
// ..... other plugins options
legend: {
display: false
}
}
对于第二个问题,你可以用chartjs-plugin-annotation
在加载插件后,例如从CDN加载插件(根据包含它的方式,您还将提供注册插件-CDN脚本不需要),您可以定义如下行:
plugins: {
// .... other plugin options
annotation: {
annotations: {
line1: {
type: 'line',
yMin: 2.4,
yMax: 2.4,
borderColor: 'rgb(255, 99, 132)',
borderWidth: 2,
}
}
}
}
代码片段:
const dates = Array.from({
length: 16
},
(_, i) => ({
x: '' + (Math.floor(new Date().valueOf() / 1000) + 24 * 3600 * i),
y: 50 * Math.exp(-(i - 8) * (i - 8)) - Math.random() * 20
}))
new Chart('chart1', {
type: 'line',
data: {
datasets: [{
data: dates,
borderWidth: 2
}],
//labels: ['a', 'b']
},
options: {
responsive: true,
maintainAspectRatio: false,
elements: {
point: {
radius: 0
}
},
plugins: {
tooltip: {
enabled: false
},
legend: {
display: false
},
annotation: {
annotations: {
line1: {
type: 'line',
yMin: 2.4,
yMax: 2.4,
borderColor: 'rgb(255, 99, 132)',
borderWidth: 2,
}
}
}
}
}
});
<div style="min-height: 300px">
<canvas id="chart1">
</canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.js" integrity="sha512-6HrPqAvK+lZElIZ4mZ64fyxIBTsaX5zAFZg2V/2WT+iKPrFzTzvx6QAsLW2OaLwobhMYBog/+bvmIEEGXi0p1w==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/3.0.1/chartjs-plugin-annotation.min.js" integrity="sha512-Hn1w6YiiFw6p6S2lXv6yKeqTk0PLVzeCwWY9n32beuPjQ5HLcvz5l2QsP+KilEr1ws37rCTw3bZpvfvVIeTh0Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
or fiddle个
当然,如果没有插件,您可以很好地定义第二个数据集,在第一个数据集的x
间隔的末尾有两个点,所需的值为y
--jsFiddle