如何隐藏顶部的数据标签并绘制一条线性线(在背景中)
y = 0
使用与数据集不同的颜色(以红色水平线显示)
我还想画第二条
dotted
水平线来指示平均水平(例如。y = 2.4
)
new Chart(canvas_id, {
type: 'line',
data: {
datasets: [{
data: dates,
borderWidth: 2
}],
//labels: ['a', 'b']
},
options: {
responsive: true,
maintainAspectRatio: false,
elements: {
point: {
radius: 0
}
},
plugins: {
tooltip: {
enabled: false
}
}
}
});
对于第一个问题,您必须禁用图例:
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>