我设置了2个图表-一个是带有onClick动作的饼图,另一个是空折线图。我目前正在使用随机数据填充图表。我想做的是通过单击饼图段来为折线图生成随机数据。我还试图将饼图段的标签传递给折线图,以便生成的数据具有与单击的标签相同的标签。到目前为止,这是我的代码:
//Pie Chart
var ctx = document.getElementById("trackingPie2").getContext("2d");
var selectedIndex = null;
window.trackingPie2 = new Chart(ctx, {
type: "doughnut",
data: pieChartData2,
options: {
responsive:false,
maintainAspectRatio: false,
title: {
display: true,
text: ["Dataset1"]
},
legend: {
position: 'bottom'
},
onClick: function (evt, elements) {
if (elements && elements.length) {
var segment = elements[0];
trackingPie2.update();
if (selectedIndex !== segment["_index"]) {
selectedIndex = segment["_index"];
segment._model.outerRadius += 10;
}
else {
selectedIndex = null;
}
}
},
layout: {
padding: 0
}
}
});
//Line Chart
var config = {
type: "line",
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August'],
},
options: {
responsive:true,
maintainAspectRatio: true,
title: {
display: true,
text: 'Dataset 2'
},
legend: {
position: 'bottom'
}
}
};
var ctx = document.getElementById("linePieChart").getContext("2d");
window.linePieChart1 = new Chart(ctx, config);
var colorNames = Object.keys(window.chartColors);
document.getElementById('trackingPie2').onClick = function(evt) {
var activePoints = trackingPie2.getSegmentsAtEvent(evt);
if(Object.keys(activePoints).length > 0) {
var label = activePoints[0]['label'];
}
var colorName = colorNames[config.data.datasets.length % colorNames.length];
var newColor = window.chartColors[colorName];
var newDataset = {
label: label,
backgroundColor: newColor,
borderColor: newColor,
data: [],
fill: false
};
for (var index = 0; index < config.data.labels.length; ++index) {
newDataset.data.push(randomScalingFactor());
}
config.data.datasets.push(newDataset);
window.linePieChart1.update();
};
我单击饼形图,但没有任何反应,但没有任何控制台错误。我似乎看不出问题出在哪里。
非常感谢您的帮助。
答案 0 :(得分:0)
我通过在饼图的点击功能中使用以下代码设法解决了自己的问题:
var activePoints = window.trackingPie2.getElementsAtEventForMode(evt, 'point',
window.trackingPie1.options);
var firstPoint = activePoints[0];
var label = window.trackingPie2.data.labels[firstPoint._index];
我添加了“窗口”。调用饼图,并使用“ getElementsAtEventForMode”而不是“ getElementAtEvent”来获取数据。