4👍
✅
Adding custom properties in JSON is a feature that may be on the roadmap for v2 (https://github.com/nnnick/Chart.js/issues/1185). As it currently stands, you can add properties in javascript doing something like this:
var segments = chart.segments;
for (var i = 0; i < segments.length; i++) {
segments[i].filter = i+1;
}
Here’s a jsfiddle with the filter/id property loading in the url (http://jsfiddle.net/tcy74pcc/1/):
If you want to do this with a chart based on points rather than segments, here’s a post with a similar solution for lines:
Displaying custom dataset properties in tooltip in chart.js
Hope that helps. Best of luck!
2👍
getSegmentsAtEvent is now deprecated. Use getElementsAtEvent instead.
Here’s the complete function with added bonus of having dynamic colors for each segment.
var piChart = function (ctx, labelName, labels, values, filters) {
var colors = dynamicColors(values.length)
var data = {
labels: labels,
datasets: [
{
label: labelName,
backgroundColor: colors.backColors,
hoverBackgroundColor: colors.highColors,
borderColor: colors.borders,
hoverBorderColor: colors.borders,
borderWidth: 1,
data: values
}
]
};
var pieChart = new Chart(ctx, {
type: "pie",
data: data
});
if (filters != null) {
ctx.click(
function (evt) {
var activePoints = pieChart.getElementAtEvent(evt);
if (activePoints.length > 0) {
var index = activePoints[0]["_index"];
location.href = filters[index];
}
});
}
}
var dynamicColors = function (count) {
var backColors = [];
var highColors = [];
var borders = [];
for (var i = 0; i < count; i++) {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
var backColor = "rgba(" + r + "," + g + "," + b + ", 0.4)";
var highColor = "rgba(" + r + "," + g + "," + b + ", 0.8)";
var border = "rgba(" + r + "," + g + "," + b + ", 1)";
backColors.push(backColor);
highColors.push(highColor);
borders.push(border);
}
Source:stackexchange.com