带有注释的chartjs:任意x位置的多条垂直线,带有标签。 示例适用于“https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@1” 但不适用于“https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@1”:缺少行标记。
两种情况下的Chartjs版本都是chartjs-4.x.x
简短:使用plugin-annotation@1标记可以 - 没有使用plugin-annotation@3标记
示例:
<!DOCTYPE html>
<html>
<head>
<title>Chart.js Line Chart with Annotations</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@1"></script>
</head>
<body>
<p>plugin-annotation@1 - no tags with plugin-annotation@3</p>
<canvas id="myChart" width="400" height="200"></canvas>
<script>
// labels from 1 to 35
const labels = Array.from({ length: 35 }, (_, i) => (i + 1).toString());
// sample data for the chart
const dataPoints = labels.map(label => Math.random() * 100);
// Data for chart
const data = {
labels: labels,
datasets: [{
label: 'Sample Data',
data: dataPoints,
borderColor: 'blue',
fill: false
}]
};
// Config for chart
const config = {
type: 'line',
data: data,
options: {
scales: {
x: { beginAtZero: true },
y: { beginAtZero: true }
},
plugins: {
annotation: {
annotations: genVertLines(labels)
}
}
}
};
// Generate vertical lines at all x-positions ending with '3'
function genVertLines(labels) {
const vertLines = labels.filter(label => label.endsWith('3')).map((label, index) => ({
type: 'line',
mode: 'vertical',
scaleID: 'x',
value: label,
borderColor: 'red',
borderWidth: 2,
label: {
content: "Label-"+label,
enabled: true,
}
}));
return vertLines;
}
// Create the chart
window.onload = function() {
const ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, config);
};
</script>
</body>
</html>
我正在搜索带有标签的示例,但只找到了plugin-annotation1.0.2
感谢您的阅读和评论。
解决方案:
<!DOCTYPE html>
<html>
<head>
<title>Chart.js Line Chart with Annotations</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@3"></script>
</head>
<body>
<canvas id="myChart" width="400" height="200"></canvas>
<script>
// labels from 1 to 35
const labels = Array.from({ length: 35 }, (_, i) => (i + 1).toString());
// sample data for the chart
const dataPoints = labels.map(label => Math.random() * 100);
// Data for chart
const data = {
labels: labels,
datasets: [{
label: 'Sample Data',
data: dataPoints,
borderColor: 'blue',
fill: false
}]
};
const vertLines = genVertLines(labels, '3');
console.log(vertLines);
// Config
const config = {
type: 'line',
data: data,
options: {
plugins: {
annotation: {
annotations:
vertLines,
}
}
}
};
function genVertLines(labels, sfx) {
const vLines = labels.filter(label => label.endsWith(sfx)).map((label, index) => ({
type: 'line',
mode: 'vertical',
scaleID: 'x',
value: label,
label: {
content: "Label-"+label,
display: true,
}
}));
return vLines;
}
// Create the chart
window.onload = function() {
const ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, config);
};
</script>
</body>
</html>
结果: