gpt4 book ai didi

javascript - Chart.js 多数据集

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:40:27 24 4
gpt4 key购买 nike

我对 Chart.js 有疑问。

我想要一个警报,当我点击图表中的一个点时显示数据集中设置的 ID 值。

我已经尝试使用 getElementsAtEvent(evt);,但它没有像我预期的那样工作。

有人可以帮助我吗?谢谢!

var ctx = document.getElementById("myChart");
var color = ["#ff6384", "#5959e6", "#2babab", "#8c4d15", "#8bc34a", "#607d8b", "#009688"];

var scatterChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Linea A',
backgroundColor: "transparent",
borderColor: color[1],
pointBackgroundColor: color[1],
pointBorderColor: color[1],
pointHoverBackgroundColor: color[1],
pointHoverBorderColor: color[1],
data: [{
x: "2014-09-02",
y: 90,
id: '1A'
}, {
x: "2014-11-02",
y: 96,
id: '2A'
}, {
x: "2014-12-03",
y: 97,
id: '3A'
}]
},
{
label: 'Linea B',
backgroundColor: "transparent",
borderColor: color[2],
pointBackgroundColor: color[2],
pointBorderColor: color[2],
pointHoverBackgroundColor: color[2],
pointHoverBorderColor: color[2],
data: [{
x: "2014-09-01",
y: 96,
id: "1B"
}, {
x: "2014-10-04",
y: 95.8,
id: "2B"
}, {
x: "2014-11-06",
y: 99,
id: "3B"
}]
}
]
},
options: {
title: {
display: true,
text: 'Polveri',
fontSize: 18
},
legend: {
display: true,
position: "bottom"
},
scales: {
xAxes: [{
type: 'time',
time: {
displayFormats: {
'millisecond': 'MM/YY',
'second': 'MM/YY',
'minute': 'MM/YY',
'hour': 'MM/YY',
'day': 'MM/YY',
'week': 'MM/YY',
'month': 'MM/YY',
'quarter': 'MM/YY',
'year': 'MM/YY',
},
tooltipFormat: "DD/MM/YY"
}
}]
}
}
});

document.getElementById("myChart").onclick = function(evt) {
var activePoints = scatterChart.getElementsAtEvent(evt);
var firstPoint = activePoints[1];
console.log(firstPoint._datasetIndex);
console.log(firstPoint._index);
var label = scatterChart.data.labels[firstPoint._index];
console.log(scatterChart.data.datasets[0].data[0].id);
var value = scatterChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
if (firstPoint !== undefined)
alert(label + ": " + value);
};
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js">
</script>
<canvas id="myChart" width="400" height="100"></canvas>

最佳答案

你必须改变你的 label 变量赋值,

var label = scatterChart.data.labels[firstPoint._index];

为了,

var label = scatterChart.data.datasets[firstPoint._index].label;

您可能还需要更改您的alert 声明,

alert(label + ": " + value.x);

这是工作演示: https://jsfiddle.net/dt6c9jev/

希望这对您有所帮助!

关于javascript - Chart.js 多数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43085672/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com