gpt4 book ai didi

javascript - 堆叠条形图上的单击事件 - ChartJs

转载 作者:数据小太阳 更新时间:2023-10-29 04:57:56 25 4
gpt4 key购买 nike

我正在尝试在堆叠条形图上实现点击事件。

数据如下所示:

var chartData = {
type: 'horizontalBar',
data: {
labels: ['A0224', 'A3681', 'A3984', 'A4101', 'A4150', 'B0682', 'Others'],
datasets: [
{
label: "P1",
backgroundColor: '#cc3399',
data: [6, 7, 6, 8, 6, 10, 3]
},
{
label: "P2",
backgroundColor: '#0099ff',
data: [8, 9, 5, 8, 6, 10, 3]
},
{
label: "P3",
backgroundColor: '#0022ff',
data: [6, 7, 6, 8, 6, 10, 3]
}
]
},
options: {
legend: { display: false },
scales: {
yAxes: [{
stacked: true
}],
xAxes: [{
stacked: true
}]
},

}
}

点击事件和图表创建方法如下所示:

var myChart = new
Chart(document.getElementById("createCurrYearHccGapChart"),
chartData);
var canvas = document.getElementById('createCurrYearHccGapChart');
canvas.onclick = function (evt) {
var activePoints = myChart.getElementsAtEvent(evt);
var cdata = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = cdata.datasets[idx].label;
var value = cdata.datasets[0].data[idx];
};

图表如下所示:

Stacked bar chart

以下是我点击单个条形图时得到的值:
第 1 条 - 标签 = P1,值 = 6
第 2 条 - 标签 = P2,值 = 7
第 3 条 - 标签 = P3,值 = 6 等等...

问题:
因此,无论我点击第一个条形图,标签都是 P1,因为我得到的索引值为整个条形图的 0 和 1 条形图 2 的索引值,依此类推。

问题:
有什么方法可以识别x坐标值吗?这样我就可以确定点击来自哪个堆栈。

最佳答案

您可以使用图表的以下单击 事件处理程序来完成此操作...

canvas.onclick = function(evt) {
var activePoint = myChart.getElementAtEvent(evt)[0];
var data = activePoint._chart.data;
var datasetIndex = activePoint._datasetIndex;
var label = data.datasets[datasetIndex].label;
var value = data.datasets[datasetIndex].data[activePoint._index];
};

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ⧩

var chartData = {
type: 'horizontalBar',
data: {
labels: ['A0224', 'A3681', 'A3984', 'A4101', 'A4150', 'B0682', 'Others'],
datasets: [{
label: "P1",
backgroundColor: '#cc3399',
data: [6, 7, 6, 8, 6, 10, 3]
}, {
label: "P2",
backgroundColor: '#0099ff',
data: [8, 9, 5, 8, 6, 10, 3]
}, {
label: "P3",
backgroundColor: '#0022ff',
data: [6, 7, 6, 8, 6, 10, 3]
}]
},
options: {
responsive: false,
legend: {
display: false
},
scales: {
yAxes: [{
stacked: true
}],
xAxes: [{
stacked: true
}]
},

}
}

var canvas = document.getElementById('createCurrYearHccGapChart');
var myChart = new Chart(canvas, chartData);

canvas.onclick = function(evt) {
var activePoint = myChart.getElementAtEvent(evt)[0];
var data = activePoint._chart.data;
var datasetIndex = activePoint._datasetIndex;
var label = data.datasets[datasetIndex].label;
var value = data.datasets[datasetIndex].data[activePoint._index];
console.log(label, value);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="createCurrYearHccGapChart" height="170"></canvas>

关于javascript - 堆叠条形图上的单击事件 - ChartJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44585862/

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