如何使用 ChartJS 向下钻取图表?
How to drill down charts with ChartJS?
我很惊讶我几乎找不到关于这个主题的信息。
我有一个 ChartJS 饼图,我想在单击饼图的一部分后深入查看它。
你会怎么做?
谢谢
我已经使用这个很棒的答案解决了我的问题:
Click events on Pie Charts in Chart.js
代码:
$(document).ready(function() {
var canvas = document.getElementById("myChart");
var ctx = canvas.getContext("2d");
var myNewChart = new Chart(ctx, {
type: 'pie',
data: data
});
canvas.onclick = function(evt) {
var activePoints = myNewChart.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
var value = chartData.datasets[0].data[idx];
var color = chartData.datasets[0].backgroundColor[idx]; //Or any other data you wish to take from the clicked slice
alert(label + ' ' + value + ' ' + color); //Or any other function you want to execute. I sent the data to the server, and used the response i got from the server to create a new chart in a Bootstrap modal.
}
};
});
效果很好。我没有提醒信息,而是使用 AJAX 将其发送到服务器,并以 bootstrap 模式显示新图表。
我很惊讶我几乎找不到关于这个主题的信息。
我有一个 ChartJS 饼图,我想在单击饼图的一部分后深入查看它。
你会怎么做?
谢谢
我已经使用这个很棒的答案解决了我的问题:
Click events on Pie Charts in Chart.js
代码:
$(document).ready(function() {
var canvas = document.getElementById("myChart");
var ctx = canvas.getContext("2d");
var myNewChart = new Chart(ctx, {
type: 'pie',
data: data
});
canvas.onclick = function(evt) {
var activePoints = myNewChart.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
var value = chartData.datasets[0].data[idx];
var color = chartData.datasets[0].backgroundColor[idx]; //Or any other data you wish to take from the clicked slice
alert(label + ' ' + value + ' ' + color); //Or any other function you want to execute. I sent the data to the server, and used the response i got from the server to create a new chart in a Bootstrap modal.
}
};
});
效果很好。我没有提醒信息,而是使用 AJAX 将其发送到服务器,并以 bootstrap 模式显示新图表。